微软在发布VS2012的同时推出了C#5.0,其中包含了async和await
编写测试代码如下:
class Program
{
private static readonly Stopwatch watch = new Stopwatch();
static void Main(string[] args)
{
watch.Start(); //UI 1
Console.WriteLine($"开始:{watch.ElapsedMilliseconds} ms"); //UI 2
TestFunc(); //UI 3
Console.WriteLine($"结束:{watch.ElapsedMilliseconds} ms"); //UI 7
Console.Read(); //UI 8
}
public static async void TestFunc()
{
await doSomething(); //UI 4
Console.WriteLine($"TestFunc完成 {watch.ElapsedMilliseconds} ms"); //thread 11
}
public static async Task doSomething()
{
Console.WriteLine($"开始调用doSomething:{watch.ElapsedMilliseconds} ms"); //UI 5
await Task.Run(new Action(() => //UI 6 ,注意开始跳转了
{
var s = "";
for (int x = 0; x < 40000; x++) //thread 8
{
s += x;
}
Console.WriteLine($"模拟耗时完成:{watch.ElapsedMilliseconds}ms"); //thread 9
}));
Console.WriteLine($"doSomething方法完成:{watch.ElapsedMilliseconds} ms"); //thread 10
}
}
执行结果:
使用注释的UI 1-8来标志UI线程的执行顺序
使用thread 9-11来标志子线程的执行顺序,关键是task执行完后,顺带的thread 10这句代码也会成为子线程来执行
但是UI 5这句代码就是由主线程执行的
也就是在开始线程前,都是由主线程执行,但是线程执行完后,剩下的代码会由子线程执行
await 后跟的方法,必须是返回类型为async Task或者 async Task<T>,不能是async void
await 所在的方法,必须为async void 或者async Task, async Task<T>await和async的核心在于await,没有await,写了async没有什么意义,还是会以主线程一直同步执行
await后跟的方法,应该是要开启线程的,没有开启线程的话,就没有必要使用await,还是会以主线程一直同步执行
await 返回到哪一句代码:
awiat标注的语句的方法必定是async修饰的
会立刻返回到一直往上找,找到第一个没有使用async标注方法里面
未完待续。。。。。