这个例子非常清楚地说明了差异。使用 async/await 调用线程不会阻塞并继续执行。
static void Main(string[] args)
{
WriteOutput("Program Begin");
// DoAsTask();
DoAsAsync();
WriteOutput("Program End");
Console.ReadLine();
}
static void DoAsTask()
{
WriteOutput("1 - Starting");
var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime);
WriteOutput("2 - Task started");
t.Wait();
WriteOutput("3 - Task completed with result: " + t.Result);
}
static async Task DoAsAsync()
{
WriteOutput("1 - Starting");
var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime);
WriteOutput("2 - Task started");
var result = await t;
WriteOutput("3 - Task completed with result: " + result);
}
static int DoSomethingThatTakesTime()
{
WriteOutput("A - Started something");
Thread.Sleep(1000);
WriteOutput("B - Completed something");
return 123;
}
static void WriteOutput(string message)
{
Console.WriteLine("[{0}] {1}", Thread.CurrentThread.ManagedThreadId, message);
}
DoAsTask 输出:
[1] 节目开始
[1] 1 - 开始
[1] 2 - 任务开始
[3] A - 开始做某事
[3] B - 完成某事
[1] 3 - 任务完成,结果:123
[1] 程序结束
DoAsAsync 输出:
[1] 节目开始
[1] 1 - 开始
[1] 2 - 任务开始
[3] A - 开始做某事
[1] 程序结束
[3] B - 完成某事
[3] 3 - 任务完成,结果:123
更新:通过在输出中显示线程 ID 来改进示例。