AutoResetEvent 一个体现通知机制的例子

来源:互联网 发布:json格式http协议通信 编辑:程序博客网 时间:2024/05/22 12:50

例子描述:两个线程,一个线程给公共变量附值后,通知另一个等待的线程把公共变量读出来。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;namespace WindowsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        //创建一个事件变量,初始状态为无信号        public static AutoResetEvent myRestEvent = new AutoResetEvent(false);        //公共存储变量        public static int number = 0;        private void button1_Click(object sender, EventArgs e)        {            Thread.CurrentThread.Name = "写线程";            //创建一个读取公共存储变量的读线程            Thread myReadThread = new Thread(new ThreadStart(MyReadThreadProc));            myReadThread.Name = "读线程";            myReadThread.Start();            //循环把I值 附给 公共存储变量            for (int i = 0; i < 100; i++)            {                show(Thread.CurrentThread.Name + ":写入值" + i.ToString());                number = i;                myRestEvent.Set();//发送一个信号给读线程                Thread.Sleep(1); //给读线程一个操作时间,不写显示就会乱。            }            myReadThread.Abort(); //因为读线程是一个死循环,所以要用Abort终止读线程        }        public void MyReadThreadProc()        {            while (true)            {                myRestEvent.WaitOne(); //停止往下执行直到信号到来                show(Thread.CurrentThread.Name + ":读到值" + number.ToString());//信号来了后,执行读公共存储的操作。            }        }        /// <summary>           ///  向主界面richTextBox1显示信息,           /// </summary>           /// <param name="message">要显示的信息</param>           /// <param name="threadname">当前线程的名字</param>           public void show(string message)        {            //richTextBox1控件的Modifiers属性要设为Public,这样才可以调用的到               this.richTextBox1.Invoke(new EventHandler(delegate            {                if (this.richTextBox1.Text.Length > 5069) this.richTextBox1.Clear();                this.richTextBox1.Text += message + Environment.NewLine;                this.richTextBox1.Select(this.richTextBox1.Text.Length, 0);                this.richTextBox1.ScrollToCaret();            }));        }    }}


原创粉丝点击