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

本文介绍了一个使用C#实现的任务执行系统,通过线程池管理并监控多个任务的执行状态。当线程池中的所有任务完成后,系统会进行相应的处理。文中详细展示了如何注册等待处理程序以及如何监控线程池的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

start:

            System.Threading.RegisteredWaitHandle rhw = null;
            new Action(() =>
            {
                for (var i = 0; i < 30; i++) {
                    new Action<int>((index) =>
                    {
                        System.Threading.Thread.Sleep(1000);
                        Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "执行完毕" + index);
                    }).BeginInvoke(i, null, null);
                }
            }).BeginInvoke(null, null);
            rhw = System.Threading.ThreadPool.RegisterWaitForSingleObject(new System.Threading.AutoResetEvent(false), new System.Threading.WaitOrTimerCallback((obj, b) =>
            {
                int workerThreads = 0;
                int maxWordThreads = 0;
                //int  
                int compleThreads = 0;
                System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
                System.Threading.ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
                //Console.WriteLine(workerThreads);
                //Console.WriteLine(maxWordThreads);
                //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成 
                if (workerThreads == maxWordThreads)
                {
                    //当执行此方法后CheckThreadPool将不再执行 
                    rhw.Unregister(null);
                    //此处加入所有线程完成后的处理代码
                    Console.WriteLine("f");
                    rhw = null;
                }
            }), null, 100, false);
            while (rhw != null) { }
            System.Threading.Thread.Sleep(10000) ;
            goto start;
            Console.WriteLine("finished");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值