线程同步信号量的使用

     //******本期测试内容:在线程同步中使用信号量********
        //声明 自动信号传达对象 AutoResetEvent 只能处理单个使用autoReset进行线程阻塞的线程
        AutoResetEvent autoReset = new AutoResetEvent(false);
        //声明 手动信号传达对象 ManualResetEvent 可以处理所有使用manualRest进行线程阻塞的线程
        ManualResetEvent manualRest = new ManualResetEvent(false);
        public ThreadTest()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            test1();
            test2();
        }
        private void test1()
        {
            Thread t = new Thread(() =>
            {
                MessageBox.Show("开始同步线程等待,等待信号传入");
                bool re = autoReset.WaitOne(10000);
                if (re)
                {
                    MessageBox.Show("收到激活线程命令");
                }
                else
                {
                    MessageBox.Show("未收到激活线程命令");
                }
            });
            t.Start();
        }
        private void test2()
        {
            Thread t = new Thread(() =>
            {
                MessageBox.Show("开始同步线程等待,等待信号传入1");
                bool re = autoReset.WaitOne(10000);
                if (re)
                {
                    MessageBox.Show("收到激活线程命令1");
                }
                else
                {
                    MessageBox.Show("未收到激活线程命令1");
                }
            });
            t.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //传递 激活线程信号,立马激活线程 跳出等待
            autoReset.Set();
        }

 AutoResetEvent 在发送完信号之后 自动将自己设置为false状态,所以  第二个线程 接收不到信号。

原文地址:https://www.cnblogs.com/scyr/p/7338081.html