C# Source Code: Example showing how to Join (synchronise) two threads
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Example showing how to Join (synchronise) two threads
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Sunday, October 10, 2004
Hits:
1870
Category:
Threading/Asynchronous operations
Article:
The Join() method blocks a given thread until the currently running thread until the thread it was called on is terminated. When the Join() method is called against a given thread instance, the thread that made the call will be placed in the WaitSleepJoin state. This method is extremely useful if a thread is dependant on another thread. When using the Join() method try to consider rewriting the code as a single thread. Since the Join() method is effectively make two threads into a single sequential task. Always ask yourself what value is being added by separating the threads. Below is an example where the thread cooking the pasta needs to wait for the thread boiling the water to finish first. using System; using System.Threading; namespace vbUsers.Threading { ///
/// Example showing how to sychronise two thread which /// are dependant on each other. ///
class JoinDemo { ///
/// Thread to boil water ///
public static Thread _threadBoilWater; ///
/// Thread to cook pasta ///
public static Thread _threadCookPasta; ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { Console.WriteLine("{0}. Starting...",DateTime.Now); _threadBoilWater = new Thread(new ThreadStart(_BoilWater)); _threadCookPasta = new Thread(new ThreadStart(_CookPasta)); _threadBoilWater.Start(); _threadCookPasta.Start(); Console.ReadLine(); } ///
/// Called by thread which boils the water ///
private static void _BoilWater() { // Boil the water Console.WriteLine("{0}. Started Boiling Water...",DateTime.Now); Thread.Sleep(3000); Console.WriteLine("{0}. Finished Boiling Water...",DateTime.Now); } ///
/// Called by thread to cook the pasta ///
private static void _CookPasta() { // YOUR CODE SHOULD DO SOME WORK HERE BEFORE CALLING THE JOIN() // METHOD, OTHERWISE YOU SHOULD BE USING A SINGLE THREAD // Fetch the pasta + peel the onions! Console.WriteLine("{0}. Preparing Pasta...",DateTime.Now); Thread.Sleep(1000); // Now wait for the water to finish boiling Console.WriteLine("{0}. Waiting for water to boil...",DateTime.Now); _threadBoilWater.Join(); Console.WriteLine("{0}. Water has boiled. Finishing meal...",DateTime.Now); Thread.Sleep(1000); Console.WriteLine("{0}. Yummy...",DateTime.Now); } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet