我试图通过在任务中调用 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
我在这里错过了什么吗?只能在任务之外取消任务吗?