繼續我期待下面的代碼打印「已取消」:取消Task.Delay(...)調用不與TaskContinuationOptions.OnlyOnCanceled
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var task = Task.Factory.StartNew(() => Proc(cts.Token), cts.Token);
task.ContinueWith(t => Console.WriteLine("Completed"), TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(t => Console.WriteLine("Cancelled"), TaskContinuationOptions.OnlyOnCanceled);
task.ContinueWith(t => Console.WriteLine("Faulted"), TaskContinuationOptions.OnlyOnFaulted);
Thread.Sleep(1000);
cts.Cancel();
Console.ReadKey();
}
static void Proc(CancellationToken token)
{
// do some CPU-intensive work
token.ThrowIfCancellationRequested();
Task.Delay(2000, token).Wait();
// do some CPU-intensive work
token.ThrowIfCancellationRequested();
}
它打印出「斷陷」,這引起了這些問題:
- 爲什麼打印「Faulted」而不是「Canceled」?
- 我濫用Task.Delay(...)作爲Thread.Sleep(...)的可取消版本嗎?
- 睡眠/延遲的正確方法是什麼,仍然對cts.Cancel()做出響應?
我故意和人爲地不使用async/await來理解TPL的工作原理。 – Wally