[关闭]
@gongzhen 2014-10-30T06:41:59.000000Z 字数 1371 阅读 2431

Task&await 执行顺序

方法定义:
  1. void Wait1()
  2. {
  3. Debug.WriteLine("start Wait1 - " + DateTime.Now);
  4. Task.Delay(5000);
  5. Debug.WriteLine("in Wait1 - " + DateTime.Now);
  6. }
  7. async void Wait2()
  8. {
  9. Debug.WriteLine("start Wait2 - " + DateTime.Now);
  10. await Task.Delay(5000);
  11. Debug.WriteLine("in Wait2 - " + DateTime.Now);
  12. }
  13. async Task Wait3()
  14. {
  15. Debug.WriteLine("start Wait3 - " + DateTime.Now);
  16. await Task.Delay(5000);
  17. Debug.WriteLine("in Wait3 - " + DateTime.Now);
  18. }
调用方式及顺序:
  1. Wait1();
  2. Debug.WriteLine("out Wait1 - " + DateTime.Now);
  3. Wait2();
  4. Debug.WriteLine("out Wait2 - " + DateTime.Now);
  5. Wait3();
  6. Debug.WriteLine("out Wait3 - " + DateTime.Now);
  7. await Wait3();
  8. Debug.WriteLine("out await Wait3 - " + DateTime.Now);
执行结果:
  1. start Wait1 - 2014/10/30 14:24:43
  2. in Wait1 - 2014/10/30 14:24:43
  3. out Wait1 - 2014/10/30 14:24:43
  4. start Wait2 - 2014/10/30 14:24:43
  5. TaskDemo.exe”(CoreCLR: .): 已加载“C:\windows\system32\en-US\mscorlib.debug.resources.dll”。模块已生成,不包含符号。
  6. System.ArgumentException”类型的第一次机会异常在 mscorlib.ni.dll 中发生
  7. System.ArgumentException”类型的第一次机会异常在 mscorlib.ni.dll 中发生
  8. out Wait2 - 2014/10/30 14:24:45
  9. start Wait3 - 2014/10/30 14:24:45
  10. out Wait3 - 2014/10/30 14:24:45
  11. start Wait3 - 2014/10/30 14:24:45
  12. in Wait2 - 2014/10/30 14:24:48
  13. in Wait3 - 2014/10/30 14:24:50
  14. in Wait3 - 2014/10/30 14:24:50
  15. out await Wait3 - 2014/10/30 14:24:50
结果说明:
  1. Wait1()由于内外都没有使用await关键字,所以内外都不会等待。

  2. Wait2()由于内部使用await关键字,外部没使用,所以只有内部等待,外部会立即执行,不会等待;Wait2()产生异常不知是否和await关键字有关,需进一步调查。

  3. Wait3()由于内部使用await关键字,外部没使用,所以只有内部等待,外部会立即执行,不会等待,同Wait2()。

  4. await Wait3()由于内外都使用了await关键字,所以内外都会进行等待。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注