zoukankan      html  css  js  c++  java
  • C# 多线程的等待所有线程结束 用 ManualResetEvent 控制

    using System;
    using System.Collections.Generic;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var waits = new List<EventWaitHandle>();
                for (int i = 0; i < 10; i++)
                {
                    var handler = new ManualResetEvent(false);
                    waits.Add(handler);
                    new Thread(new ParameterizedThreadStart(Print))
                    {
                        Name = "thread" + i.ToString()
                    }.Start(new Tuple<string, EventWaitHandle>("test print:" + i, handler));
                }
                WaitHandle.WaitAll(waits.ToArray());
                Console.WriteLine("Completed!");
                Console.Read();
    
            }
    
            private static void Print(object param)
            {
                var p = (Tuple<string, EventWaitHandle>)param;
                Console.WriteLine(Thread.CurrentThread.Name + ": Begin!");
                Console.WriteLine(Thread.CurrentThread.Name + ": Print" + p.Item1);
                Thread.Sleep(300);
                Console.WriteLine(Thread.CurrentThread.Name + ": End!");
                p.Item2.Set();
            }
    
        }
    }
    

      

  • 相关阅读:
    用户模板和用户场景
    人月神话阅读笔记02
    人月神话阅读笔记01
    软件工程周总结07
    NABCD
    软件工程周总结06
    软件工程周总结05
    tomcat端口被占用
    SQLyog出现2003错
    一维最大子数组和(续)
  • 原文地址:https://www.cnblogs.com/chengulv/p/4716206.html
Copyright © 2011-2022 走看看