C#中多线程信号控制ManualResetEvent和AutoResetEvent

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication22
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls =false ;
        }
        static AutoResetEvent AutoR = new AutoResetEvent(false);//只对一个线程设置为有信号。
       // static ManualResetEvent Manual = new ManualResetEvent(false);//对一个或多个线程设置为有信号。
       

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            AutoR.Set();//例如我在这里使用Set()方法设置为true有信号,设置完后他会自动调用Reset()方法设置为false无信号。
            //其它线程将会被AutoR.WaitOne();阻止.直到收到为有信号.

            // 这样好处在于控制单个线程还是方便的,但是对于多线程的话就麻烦了,
            // 如果多个线程中对同一个AutoResetEvent 实例的WaitOne方法将只有1个起作用。
            // 而ManualResetEvent不会主动Reset,因此此时WaitOne方法将都有效。
            // 所以绝大数情况下还是尽量使用ManualResetEvent。


            // AutoR.Set();Set()方法表示状态设为ture,让其它线程有信号执行下去。
            // AutoR.Reset();方法表示状态设为false,让其它线程无信号即不能执行下去。

            // 这就是ManualResetEvent和AutoResetEvent 的主要差别呢?


            for (int i = 1; i < 6; i++)
            {
                
                Thread td = new Thread(ok);
                td.Name = i.ToString();
                td.Start();

            }

            
        }
        public void ok()
        {

                    AutoR.WaitOne();
                    //阻止或许为等待当前线程执行。直到收到为有信号则运行。
                    //true=有信号;false=无信号.
                    textBox1.AppendText(string.Format("| 线程名字:{0} ",  Thread.CurrentThread.Name));
                    Thread.Sleep(2000);

                  
        
        }


    }
}

 

posted on 2017-07-22 19:16  LarvaAndQing  阅读(542)  评论(0编辑  收藏  举报

导航