zoukankan      html  css  js  c++  java
  • Thread.Join 和 Task.Wait 方法

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

    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

    观察运行结果,可以发现 不管是Thread还是Task,都是采用异步处理的方式在子线程里跑的

    接下来我们把 注释的两句话放开(Thread.Join 和 Task.Wait )

    再运行,观察结果,可以看到,Thread的线程已经合并到了主线程中,阻塞了主线程,Task异步的任务也变成了阻塞型。

    两个方法用起来还是很简单的,这样就很清楚了。

  • 相关阅读:
    noip2014提高组day2二题题解-rLq
    uva 1606 amphiphilic carbon molecules【把缩写写出来,有惊喜】(滑动窗口)——yhx
    NOIP2008提高组(前三题) -SilverN
    uva 11134 fabled rooks (贪心)——yhx
    NOIP2008提高组火柴棒等式(模拟)——yhx
    NOIP2008 普及组T2 排座椅 解题报告-S.B.S
    判断https
    redis 在centos下的安装部署
    phpstorm常用快捷键
    yii 打印sql
  • 原文地址:https://www.cnblogs.com/wolfworker/p/7611585.html
Copyright © 2011-2022 走看看