【发布时间】:2014-04-10 19:41:13
【问题描述】:
C# 提供了两种创建异步方法的方式:
Task():
static Task<string> MyAsyncTPL() {
Task<string> result = PerformWork();
return result.ContinueWith(t => MyContinuation());
}
async Task():
static async Task<string> MyAsync() {
string result = await PerformWork();
return MyContinuation();
}
以上两种方法都是async,实现相同的目的。那么,我什么时候应该选择一种方法而不是另一种方法?使用其中一种是否有任何指导方针或优势?
【问题讨论】:
-
您的示例不一样 - 如果从
PerformWork返回的任务失败或被取消,它们的行为会有所不同。 -
或者如果有一个当前的
SynchronizationContext。或者如果返回的任务被用作父任务。或者可能是await比ContinueWith处理得更体面的其他一些晦涩的角落案例。
标签: c# .net asynchronous task