这两个方法 可以说是类似的功能,都是对当前任务进行等待阻塞,执行完毕后再进行后续处理

talk is cheap, show you code,下面一个是异步执行,一个是加了阻塞,可以对比不同执行结果

 1         public static void TaskThreadTest()
 2         {
 3             Stopwatch watch = new Stopwatch();
 4             watch.Start();
 5             Thread thread = new Thread(new ThreadStart(ThreadFunction));
 6             Console.WriteLine($"Thread 开始");
 7             thread.Start();
 8             //thread.Join();
 9             watch.Stop();
10             Console.WriteLine($"Thread 耗时:{watch.ElapsedMilliseconds}");
11 
12             Stopwatch watch2 = new Stopwatch();
13             watch2.Start();
14             Console.WriteLine($"Run 开始");
15             var task = Task.Run(() =>
16             {
17                 for (int i = 0; i < 5; i++)
18                 {
19                     Thread.Sleep(5);
20                     Console.WriteLine($"{i}: Run");
21                 }
22             });
23             //task.Wait();
24             watch2.Stop();
25             Console.WriteLine($"Run 耗时:{watch2.ElapsedMilliseconds}");
26             Console.WriteLine($"All is End!");
27             Console.Read();
28         }
29 
30         public static void ThreadFunction()
31         {
32             for (int i = 0; i < 5; i++)
33             {
34                 Thread.Sleep(5);
35                 Console.WriteLine($"{i}: Thread");
36             }
37         }
View Code

相关文章: