在代码流可以继续之前,我需要取消一个待处理的任务并等待它的终止。通常,我这样做:
if (this.task != null)
{
this.taskCancellationTokenSource.Cancel();
try
{
await this.task;
// I don't need to know the result, just log it
Debug.Print(this.task.Status.ToString());
}
catch (Exception e)
{
// I don't need to know the result, just log it
Debug.Print(e.ToString());
}
}
我刚刚意识到我可以在没有以下情况下做同样的事情try/catch
:
if (this.task != null)
{
this.taskCancellationTokenSource.Cancel();
await this.task.ContinueWith(
// I don't need to know the result, just log it
(t) => Debug.Print(((object)t.Exception ?? (object)t.Status).ToString()),
TaskContinuationOptions.ExecuteSynchronously)
}
我错过了我应该坚持第一种方法的任何理由吗?