当新新线程不使用await修饰时:
public static void test() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 100; i++) { Console.WriteLine($"i:{i}"); } Console.WriteLine($"第一次计时:{stopwatch.ElapsedMilliseconds}"); Task.Run(() => { for (int i = 0; i < 100; i++) { Console.WriteLine($"i:{i}"); } Console.WriteLine($"第二次计时:{stopwatch.ElapsedMilliseconds}"); }); Console.WriteLine($"第三次计时:{stopwatch.ElapsedMilliseconds}"); }
所跑出来的结果:
使用await修饰新线程时:
public async static void test() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 100; i++) { Console.WriteLine($"i:{i}"); } Console.WriteLine($"第一次计时:{stopwatch.ElapsedMilliseconds}"); await Task.Run(() => { for (int i = 0; i < 100; i++) { Console.WriteLine($"i:{i}"); } Console.WriteLine($"第二次计时:{stopwatch.ElapsedMilliseconds}"); }); Console.WriteLine($"第三次计时:{stopwatch.ElapsedMilliseconds}"); }
结果: