多线程等待

温故而知新,好久没有用到,突然忘记 

方法一 CountDownEvent 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //引入线程
using System.Diagnostics; 

namespace ThreadSynchronousDemo
{
    class Program
    {
        static CountdownEvent CountDownWork = new CountdownEvent(2);      

        static void Main(string[] args)
        {

            Console.WriteLine("开始,CountdownEvent 同步");       

            var t = new Thread((() => working("第 1 个工作线程任务", 3)));
            var t2 = new Thread((() => working("第 2 个工作线程任务", 6)));

            //var t3 = new Thread((() => working("第 3 个工作线程任务", 12)));
            t.Start();
            t2.Start();
            //t3.Start();
            Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine("开始,线程工作计数");
            CountDownWork.Wait();           

            Console.WriteLine("计数完成,2个工作 已经完成!");
            //如果把上面代码注释的第三个线程还原,释放对象,可以造成第三个线程的抛出错误

            CountDownWork.Dispose();     

            Console.Read();
        } 

        static void working(string message,int seconds)
        {
            Console.WriteLine("工作前休息 {0}",DateTime.Now.Second);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine(message);          

            CountDownWork.Signal();
            Console.WriteLine("发出计数信号, 工作已经完成一项");      

        }
    }
}

  

方法二

 List<AutoResetEvent> autoResetEvents = new List<AutoResetEvent>() { new AutoResetEvent(false), new AutoResetEvent(false), };

List<AutoResetEvent> autoResetEvents = new List<AutoResetEvent>() { new AutoResetEvent(false), new AutoResetEvent(false), };

 new Thread(() =>
                {
                    //todo 

                    autoResetEvents[0].Set();//释放第一个线程
                }).Start();

 new Thread(() =>
                {
                    //todo 

                    autoResetEvents[1].Set();//释放第二个线程
                }).Start();

 WaitHandle.WaitAll(autoResetEvents.ToArray()); //等待所有线程

 

posted on 2022-11-15 09:09  永恒921  阅读(23)  评论(0编辑  收藏  举报