• C#如何判断线程池中所有的线程是否已经完成之Demo


     1 start:
     2 
     3             System.Threading.RegisteredWaitHandle rhw = null;
     4             new Action(() =>
     5             {
     6                 for (var i = 0; i < 30; i++) {
     7                     new Action<int>((index) =>
     8                     {
     9                         System.Threading.Thread.Sleep(1000);
    10                         Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "执行完毕" + index);
    11                     }).BeginInvoke(i, null, null);
    12                 }
    13             }).BeginInvoke(null, null);
    14             rhw = System.Threading.ThreadPool.RegisterWaitForSingleObject(new System.Threading.AutoResetEvent(false), new System.Threading.WaitOrTimerCallback((obj, b) =>
    15             {
    16                 int workerThreads = 0;
    17                 int maxWordThreads = 0;
    18                 //int  
    19                 int compleThreads = 0;
    20                 System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
    21                 System.Threading.ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
    22                 //Console.WriteLine(workerThreads);
    23                 //Console.WriteLine(maxWordThreads);
    24                 //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成 
    25                 if (workerThreads == maxWordThreads)
    26                 {
    27                     //当执行此方法后CheckThreadPool将不再执行 
    28                     rhw.Unregister(null);
    29                     //此处加入所有线程完成后的处理代码
    30                     Console.WriteLine("f");
    31                     rhw = null;
    32                 }
    33             }), null, 100, false);
    34             while (rhw != null) { }
    35             System.Threading.Thread.Sleep(10000) ;
    36             goto start;
    37             Console.WriteLine("finished");
  • 相关阅读:
    fork 入门
    java 注解 @Retention @interface 元数据
    JAVA泛型简析
    http数据流 gzip解压方法分析
    gdb调试提示 Missing separate debuginfos
    Vue2.x响应式原理
    观察者模式
    优秀博客收集
    切换npm源的方式
    前端模块化之ES Module
  • 原文地址:https://www.cnblogs.com/yomho/p/3870221.html
Copyright © 2020-2023  润新知