C# Source Code: Using event-based synchronisation across multiple threads
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Using event-based synchronisation across multiple threads
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, April 08, 2004
Hits:
562
Category:
Threading/Asynchronous operations
Article:
There are two classes available to provide event-based synchronisation, the AutoResetEvent and the ManualResetEvent. Both of these classes block threads until a specific event has occureed. The only difference is that the AutoResetEvent class automatically returns to a "Not Signaled" state after the first wait request has been granted. Below is an example which shows how to synchronise two threads to wait for a database connection before continuing: using System; using System.Threading; //Copyright Andrew Baker (www.vbusers.com) namespace vbUsers.Threading { //This class demonstrates how to use synchronisation events to block a thread until a particular //event has occurred class DemoTheadSynchronisation { [STAThread] static void Main(string[] args) { Console.WriteLine("Thread {0}. Starting Application...",AppDomain.GetCurrentThreadId()); DatabaseConnector oDB = new DatabaseConnector(); //Create new database connection thread Thread thConnect = new Thread(new ThreadStart(oDB.Connect)); //Start the connection thread thConnect.Start(); //Do other work here (while the database is connecting) Console.WriteLine("Thread {0}. Doing other intialisation work...",AppDomain.GetCurrentThreadId()); //Now wait for the connection to finish before continuing Console.WriteLine("Thread {0}. Waiting for Database Connection...",AppDomain.GetCurrentThreadId()); oDB.WaitForConnection.WaitOne(); Console.WriteLine("Thread {0}. Finished waiting for Connection...",AppDomain.GetCurrentThreadId()); //Pause to show the results Thread.Sleep(5000); } } //Class to simulate connecting to a database public class DatabaseConnector { /* Create the manual event as "Not Signaled". This means the WaitHandle isn't available until the Set method is called. So a thread calling the WaitOne method will be remain in a suspended state until the Set method is called. */ public ManualResetEvent WaitForConnection = new ManualResetEvent(false); public void Connect() { //Simulate connecting to database Console.WriteLine("Thread {0}. Connecting Database...",AppDomain.GetCurrentThreadId()); Thread.Sleep(2000); //Notify any threads that are waiting after calling the WaitOne method that the connection //has been established Console.WriteLine("Thread {0}. Finished Connecting Database...",AppDomain.GetCurrentThreadId()); //Release wait handle WaitForConnection.Set(); } public void Disconnect() { //Reset the event (to Not Signaled) as the event will remain Signaled after Connect has been called. WaitForConnection.Reset(); } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet