在下面的代碼上調用await RunAsync();
時,我期待繼續運行TaskContinuationOptions.OnlyRanToCompletion
繼續,但OnlyOnCanceled
延續被調用(產生調試輸出「任務取消」)。爲什麼OnlyOnCanceled延續被調用?
爲什麼?
private static async Task RunAsync()
{
try
{
await Task.Run(() => DoWork())
.ContinueWith(
(t) =>
{
if (t?.Exception != null)
{
throw t.Exception;
}
}, TaskContinuationOptions.OnlyOnFaulted
).ContinueWith(
(t) =>
{
Debug.WriteLine("Task canceled.");
}, TaskContinuationOptions.OnlyOnCanceled
).ContinueWith(
(t) =>
{
Debug.WriteLine("Task completed.");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private static void DoWork()
{
Thread.Sleep(1000);
}