4
我有下面的代碼示例:取消等待本身
public static async Task Async()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(500);
Stopwatch sw = Stopwatch.StartNew();
await RunThread(ExpensiveOperation, source.Token);
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
public static async Task RunThread(Action act, CancellationToken token)
{ //modify this method to handle cancelling the token during the following await
await Task.Run(act); //Task.Run(act, token) doesn't help
}
public static void ExpensiveOperation()
{
Thread.Sleep(1000); //simulates CPU expensive operation
}
現在,我怎麼能修改RunThread
方法真正停止被取消,等待已久的任務,通過註冊任務,之後那些那麼回事500毫秒,不等待ExpensiveOperation
的實際完成?
@downvoter,錯了什麼? – i3arnon 2015-02-09 21:25:56
如果任務在task.IsCompleted時尚未完成,但是在task.ContinueWith之前,WithCancellation方法會遇到麻煩嗎? – IllidanS4 2015-02-09 21:38:26
@ IllidanS4 no。你總是可以使用'ContinueWith'。檢查'IsCompleted'只是一個優化,不會因爲任務已完成而煩惱註冊。 – i3arnon 2015-02-09 21:40:46