码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-22 21:18:43      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:表示   class   好处   int   data   ace   eric   click   event   

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);

                  
        
        }


    }
}

 

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

标签:表示   class   好处   int   data   ace   eric   click   event   

原文地址:http://www.cnblogs.com/larva/p/7222344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!