WaitHandle

来源:互联网 发布:bim软件分类 编辑:程序博客网 时间:2024/05/29 02:08
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 WaitHadle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            cThread = new System.Threading.Thread(Cal);
            cThread.Priority = System.Threading.ThreadPriority.Highest;
            cThread.Start();
        }
        private System.Threading.Thread cThread;
        //通知正在等待的线程已发生事件
        private AutoResetEvent m_cAtReset = new AutoResetEvent(false);
        private void buttonX1_Click(object sender, EventArgs e)
        {              
            AutoResetEvent[] evs = { m_cAtReset };
            System.Diagnostics.Debug.WriteLine("等待计算");
            //等待指定数组中的任一元素收到信号,使用 32 位有符号整数度量时间间隔并指定是否在等待之前退出同步域。
            int index = WaitHandle.WaitAny(evs, 10000, false);
            System.Diagnostics.Debug.WriteLine("得到计算值显示");
            if (index == 0)
            {
                labelX1.Text = sum.ToString();
            }
        }
        private int sum = 0;
        private void Cal()
        {     
            for (int i = 0; i < 100; i++)
            {
                sum += i;
                Thread.Sleep(100);
                if (sum > 2000)
                {
                    System.Diagnostics.Debug.WriteLine("计算完毕");
                    //将事件状态设置为终止状态,允许一个或多个等待线程继续。
                    if (sum > 4000)
                    {
                        m_cAtReset.Set();
                    }
                    else
                    {
                        //将事件状态设置为非终止状态,导致线程阻止。
                        m_cAtReset.Reset();
                    }
                    System.Diagnostics.Debug.WriteLine("发送计算值");
                }
            }
        }
    }
}
0 0