c#线程基础之线程控制

http://blog.youkuaiyun.com/jinjazz/archive/2008/06/20/2569254.aspx

c#线程基础之线程控制 收藏
用ManualResetEvent和AutoResetEvent可以很好的控制线程的运行和线程之间的通信。msdn的参考为: http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.aspx http://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx 下面我写个例子,这里模拟了一个线程更新数据,两个线程读取数据。更新的时候需要阻止读取的两个现成工作。而另外还有一个信号量来控制线程的退出。

view plaincopy to clipboardprint?
using System;  
 
using System.Collections.Generic;  
 
using System.ComponentModel;  
 
using System.Data;  
 
using System.Drawing;  
 
using System.Text;  
 
using System.Windows.Forms;  
 
 
 
namespace WindowsApplication35  
 
{  
 
    public partial class Form1 : Form  
 
    {  
 
        public Form1()  
 
        {  
 
            InitializeComponent();  
 
        }  
 
 
 
        System.Threading.ManualResetEvent mEvent = new System.Threading.ManualResetEvent(true);  
 
 
 
        //判断线程安全退出的信号量  
 
        System.Threading.ManualResetEvent mEventStopAll = new System.Threading.ManualResetEvent(false);  
 
 
 
        //*******ManualResetEvent的用法。  
 
        private void button1_Click(object sender, EventArgs e)  
 
        {  
 
            //一个线程模拟写入  
 
            new System.Threading.Thread(invokeWrite).Start();  
 
            //两个线程模拟读取  
 
            new System.Threading.Thread(invokeRead).Start();  
 
            new System.Threading.Thread(invokeRead).Start();  
 
        }  
 
 
 
        private void invokeWrite()  
 
        {  
 
            for (int i = 0; i < 100; i++)  
 
            {  
 
                //判断线程安全退出  
 
                if (mEventStopAll.WaitOne(10, false) == true) break;  
 
                //设置信号量,假设更新数据需要2秒,每更新一次暂停2秒.  
 
                mEvent.Reset();  
 
                Console.WriteLine("正在更新...");  
 
                System.Threading.Thread.Sleep(2000);  
 
                mEvent.Set();  
 
                System.Threading.Thread.Sleep(2000);  
 
            }  
 
        }  
 
        private void invokeRead()  
 
        {  
 
            while (mEvent.WaitOne() == true)  
 
            {  
 
                //判断线程安全退出  
 
                if (mEventStopAll.WaitOne(10, false) == true) break;  
 
                //假设读取一体数据用10毫秒.他需要判断信号量开关.  
 
                Console.WriteLine("读取一条数据:");  
 
                System.Threading.Thread.Sleep(10);  
 
            }  
 
        }  
 
 
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
 
        {  
 
            mEventStopAll.Set();  
 
        }  
 
    }  
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值