用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 下面我寫個例子,這裡類比了一個線程更新資料,兩個線程讀取資料。更新的時候需要阻止讀取的兩個現成工作。而另外還有一個訊號量來控制線程的退出。
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(); } }}