我正在尝试通过在任务内调用CancellationTokenSource.Cancel()方法来取消一个Task<>,但是我无法使它工作。
这是我使用的代码:
TaskScheduler ts = TaskScheduler.Current;
CancellationTokenSource cts = new CancellationTokenSource();
Task t = new Task( () =>
{
Console.WriteLine( "In Task" );
cts.Cancel();
}, cts.Token );
Task c1 = t.ContinueWith( antecedent =>
{
Console.WriteLine( "In ContinueWith 1" );
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, ts );
Task c2 = c1.ContinueWith( antecedent =>
{
Console.WriteLine( "In ContinueWith 2" );
}, TaskContinuationOptions.NotOnCanceled );
t.Start();
Console.ReadKey();
Environment.Exit( 1 );
这将打印输出:
In Task
In ContinueWith 1
In ContinueWith 2
我期望的是这样:
In Task
我有点不明白,任务只能在任务外部取消吗?这是什么情况?
CancellationToken.ThrowIfCancellationRequested
方法。 - Hamlet Hakobyanctrl+f5
运行几次,出现了各种输出的情况。也许这只是将结果刷新到控制台的情况。 - jwaliszko