async 和 await 异步方法

版本新特性 / C# 5.0

using System;
using System.Threading.Tasks;

class Program {
    static Task<int> LoadAsync(string name) {
        return Task.Run(() => name.Length);
    }

    // *** 以前 ***
    // 过去稍后才完成的工作要在回调中继续,
    // 所以各步骤写得倒过来,还一层套一层
    static void TotalOld(Action<int> done) {
        LoadAsync("first").ContinueWith(a => {
            LoadAsync("second").ContinueWith(b => {
                done(a.Result + b.Result);
            });
        });
    }

    // *** 在 5.0 版本中 ***
    // await 在此处把方法拆开:它返回给调用方,
    // 任务就绪后再从这里继续
    static async Task<int> TotalNew() {
        int a = await LoadAsync("first");
        int b = await LoadAsync("second");
        return a + b;
    }

    static void Main() {
        TotalOld(total => Console.WriteLine(total));
        Console.WriteLine(TotalNew().Result);

        // async 不是线程:在第一个 await 之前,方法在调用方线程上运行,
        // 任务运行期间没有线程在等待
    }
}