分享

C# EventWaitHandle用法

 牛人的尾巴 2015-12-01

C# EventWaitHandle用法

(2013-03-25 14:33:24)
    //class Program
    //{
    //    static EventWaitHandle[] ewhs;
    //    static void UserResource(object o)
    //    {
    //        int i = (int)o;
    //        ewhs[i].WaitOne();
    //        Console.WriteLine("get resource" + Thread.CurrentThread.Name);
    //        Thread.Sleep(2000);
    //        if (i + 1 < ewhs.Length)
    //        {
    //            ewhs[i + 1].Set(); //开启下一个线程的信号
    //        }
    //    }

    //    static void Main(string[] args)
    //    {
    //        int threadNum = 5;
    //        ewhs = new EventWaitHandle[threadNum]; //信号灯数组,用于分别控制多个线程的执行

    //        Thread[] threads = new Thread[threadNum];
    //        for (int i = 0; i < threadNum; i++)
    //        {
    //            string name = "ewh" + i.ToString();
    //            //EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name);     //默认信号灯都为没有信号
    //            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset, name);     //默认信号灯都为没有信号
    //            ewhs[i] = ewh;

    //            threads[i] = new Thread(new ParameterizedThreadStart(UserResource));
    //            threads[i].Name = "threads" + i.ToString();
    //            threads[i].Start(i);
    //        }
    //        ewhs[0].Set(); //开启第一个线程的信号,使其开始执行,其他线程阻塞。
    //        Console.Read();
    //    }
    //}

    class Program
    {
        static EventWaitHandle ewhs;
        static void UserResource()
        {
            ewhs.WaitOne();
            Console.WriteLine("get resource" + Thread.CurrentThread.Name);
            Thread.Sleep(2000);

            ewhs.Set();//再次开启一个线程的信号,使其开始执行,其他线程阻塞。
        }

        static void Main(string[] args)
        {
            int threadNum = 5;
            ewhs = new EventWaitHandle(false, EventResetMode.AutoReset, "eventWaitHandle"); //信号灯数组,用于分别控制多个线程的执行

            Thread[] threads = new Thread[threadNum];
            for (int i = 0; i < threadNum; i++)
            {
                string name = "ewh" + i.ToString();

                threads[i] = new Thread(new ThreadStart(UserResource));
                threads[i].Name = "threads" + i.ToString();
                threads[i].Start();
            }
            ewhs.Set(); //开启一个线程的信号,使其开始执行,其他线程阻塞。
            Console.Read();
        }
    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多