[转]C# 多线程是否结束可通过线程池可以判断

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace 线程池判断结束综合演示
{
    class Program
    {
        public static int iCount = 0;  
        public static int MaxCount = 10;//允许线程池中运行最多10个线程 
        static ManualResetEvent eventX = new ManualResetEvent(false);  //新建ManualResetEvent对象并且初始化为无信号状态

        static void Main(string[] args)
        {
            Console.WriteLine("ManualResetEvent初始为无信号状态 ");
            Console.WriteLine("线程池最大值为 {0} 个线程。", MaxCount);
            for (int iItem = 1; iItem <= MaxCount; iItem++)
            {
                //插入队列元素
                Console.WriteLine("加入线程 {0}", iItem);
                ThreadPool.QueueUserWorkItem(new WaitCallback(fun1), (object)iItem);
            }
            Console.WriteLine("等待线程池完成操作。。。"); //等待事件的完成,即线程调用ManualResetEvent.Set()方法
            eventX.WaitOne(Timeout.Infinite, true); //WaitOne()方法使调用它的线程等待直到eventX.Set()方法被调用
            Console.WriteLine("线程池结束!");
            Console.ReadLine(); 
        }

        public static void fun1(object j)
        {
            Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), j.ToString());
            Thread.Sleep(1000);
            Interlocked.Increment(ref iCount);
            if (iCount == MaxCount)
            {
                Console.WriteLine();
                Console.WriteLine("设置ManualResetEvent为有信号状态,Setting eventX ");
                eventX.Set();
            }  

        }

 

    }
}

转载于:https://www.cnblogs.com/greenwood2012/p/4813196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值