问题描述
我创建了一个演示项目,以帮助我了解如何使用取消令牌.我了解您已取消令牌并检查是否已请求取消,但是有什么方法可以检查是否已实现取消?在下面的示例中,我不想在DoWork()完成运行之前再次运行Work().
I've created a little demo project to help me understand how I can use Cancellation Tokens. I understand that you cancel a token and check if a cancellation has been requested, but is there a way that I can check whether the cancellation has been realised? In my example below, I don't want to run Work() again until DoWork() has finished running.
public class Program
{
public static CancellationTokenSource tokenSource;
private static void Main(string[] args)
{
while (true)
{
Work();
}
}
public static async void Work()
{
tokenSource = new CancellationTokenSource();
Console.WriteLine("Press any key to START doing work");
Console.ReadLine();
Console.WriteLine("Press any key to STOP doing work");
DoWork(tokenSource.Token);
Console.ReadLine();
Console.WriteLine("Stopping...");
tokenSource.Cancel();
}
public static async void DoWork(CancellationToken cancelToken)
{
while (true)
{
Console.WriteLine("Working...");
await Task.Run(() =>
{
Thread.Sleep(1500);
});
if (cancelToken.IsCancellationRequested)
{
Console.WriteLine("Work Cancelled!");
return;
}
}
}
}
推荐答案
如果您的所有操作都是异步的并且可以取消的,那么您将可以充分利用 CancellationToken
的优势.这种取消令牌的方法将立即生效.您不必等待 Thread.Sleep
或其他阻止调用完成.
You will make the most out of a CancellationToken
if all your operations are asynchronous and cancellable. This way cancelling the token will have immediate effect. You won't have to wait for a Thread.Sleep
or other blocking call to complete.
public static async Task DoWork(CancellationToken cancellationToken)
{
while (true)
{
await Console.Out.WriteLineAsync("Working...");
await Task.Delay(1500, cancellationToken);
}
}
在此示例中,令牌仅传递给 Task.Delay
,因为 WriteLineAsync
在.NET Framework上(在.NET Core上)无法取消.
In this example the token is passed only to Task.Delay
, because the WriteLineAsync
is not cancellable on .NET Framework (it is on .NET Core).
取消令牌时, Task.Delay
将引发 OperationCanceledException
.
这篇关于检查CancellationToken是否已取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!