With ManualResetEvent and AutoResetEvent, you can control the running of threads and the communication between threads. MSDN's Reference is: Http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.aspx http://msdn.microsoft.com /zh-cn/library/system.threading.manualresetevent.aspx below I write an example, here simulates a thread to update the data, two threads read the data. There are two out-of-the-box jobs that need to be blocked from reading when they are updated. There is also a semaphore to control the exit of the thread.
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);
To determine the semaphore of a thread's safe exit
System.Threading.ManualResetEvent Meventstopall = new System.Threading.ManualResetEvent (false);
The use of ManualResetEvent.
private void Button1_Click (object sender, EventArgs e)
{
One thread impersonation Write
New System.Threading.Thread (Invokewrite). Start ();
Two-thread analog reads
New System.Threading.Thread (Invokeread). Start ();
New System.Threading.Thread (Invokeread). Start ();
}
private void Invokewrite ()
{
for (int i = 0; i < i++)
{
To judge a thread to exit safely
if (Meventstopall.waitone (false) = = true) break;
Set the semaphore, assuming that the update data takes 2 seconds, pausing 2 seconds for each update.
Mevent.reset ();
Console.WriteLine ("Updating ...");
System.Threading.Thread.Sleep (2000);
Mevent.set ();
System.Threading.Thread.Sleep (2000);
}
}
private void Invokeread ()
{
while (mevent.waitone () = = True)
{
To judge a thread to exit safely
if (Meventstopall.waitone (false) = = true) break;
Suppose that read-in-one data is 10 milliseconds. He needs to judge the signal switch.
Console.WriteLine ("Read a piece of data:");
System.Threading.Thread.Sleep (10);
}
}
private void Form1_formclosing (object sender, FormClosingEventArgs e)
{
Meventstopall.set ();
}
}
}