我写了以下代码:
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
int i = 0;
Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
Task t1 = new Task(() =>
{
while (true)
{
try
{
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Console.WriteLine("Task1 cancel detected");
break;
}
Console.WriteLine("Task1: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
}
}, token);
Task t2 = new Task(() =>
{
while (true)
{
try
{
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Console.WriteLine("Task2 cancel detected");
break;
}
Console.WriteLine("Task2: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
}
});
t1.Start();
t2.Start();
Thread.Sleep(100);
tokenSource.Cancel();
t1.Wait();//wait for thread to completes its execution
t2.Wait();//wait for thread to completes its execution
Console.WriteLine("Task1 Status:{0}", t1.Status);
Console.WriteLine("Task2 Status:{0}", t1.Status);
在这里我取消任务然后状态也显示 RanToCompletion 但如果我删除两个任务的等待,那么它显示我取消状态...
当我取消任务时,无论如何我都希望取消状态......
编辑:来自 MSDN 通过抛出 OperationCanceledException 并将请求取消的令牌传递给它。执行此操作的首选方法是使用 ThrowIfCancellationRequested 方法。以这种方式取消的任务将转换到 Canceled 状态,调用代码可以使用该状态来验证任务是否响应了它的取消请求。
如果您不使用 Wait 或 WaitAll 方法来等待任务,则任务只是将其状态设置为 Canceled。