首页 > 代码库 > C# 多线程处理相关说明: WaitHandle,waitCallback, ThreadPool.QueueUserWorkItem

C# 多线程处理相关说明: WaitHandle,waitCallback, ThreadPool.QueueUserWorkItem

  class TestThread
    {
        
        static void Main()
        {
            //使用WaitHandle静态方法阻止一个线程,直到一个或多个同步对象接收到信号
            WaitHandle[] waitHandles = new WaitHandle[] 
            {
            new ManualResetEvent(false),
            new ManualResetEvent(false)
            };

            WaitCallback waitCallback = new WaitCallback(MyThreadWork);

            WaitCallback waitCallback2 = new WaitCallback(MyThreadWork2);     // 增加线程工作类型

            ThreadPool.QueueUserWorkItem(waitCallback, "第一个线程");
            ThreadPool.QueueUserWorkItem(waitCallback, "第二个线程");

            MyState myState = new MyState("第三个线程", 100, waitHandles[0]); // 增加自定义的线程参数类型

            ThreadPool.QueueUserWorkItem(waitCallback2, myState);
            ThreadPool.QueueUserWorkItem(waitCallback2, new MyState("第四个线程", 2, waitHandles[1]));

            WaitHandle.WaitAll(waitHandles);

            Console.WriteLine("MyState 的 Number 值为: {0}", myState.Number);    // 读取线程改变后的 MyState
        }

        public static void MyThreadWork(object state)
        {
            Console.WriteLine("MyThreadWork 开始启动 …… {0}", (string)state);
            Thread.Sleep(1000);
            Console.WriteLine("运行结束…… {0}", (string)state);
        }

        // use MyState class 
        public static void MyThreadWork2(object state)
        {
            MyState myState = ((MyState)state);
            Console.WriteLine("MyThreadWork2 开始启动…… {0},{1}", ((MyState)state).Info, ((MyState)state).Number);
            Thread.Sleep(1000);
            ((MyState)state).Number += 1;      // 将 state的 Number 加 1
            Console.WriteLine("运行结束…… {0},{1}", ((MyState)state).Info, ((MyState)state).Number);
            ((ManualResetEvent)myState.DoneEvent).Set();
        }

    }

    public class MyState
    {
        private string info;
        private int number;
        private WaitHandle _doneEvent;


        public MyState(string info, int number, WaitHandle doneEvent)
        {
            this.info = info;
            this.number = number;
            this._doneEvent = doneEvent;
        }

        public string Info
        {
            get
            {
                return this.info;
            }
            set
            {
                this.info = value;
            }
        }

        public WaitHandle DoneEvent
        {
            get
            {
                return this._doneEvent;
            }
        }

        public int Number
        {
            get
            {
                return this.number;
            }
            set
            {
                this.number = value;
            }
        }
    }