In his post, I want to show you one more way to synchronise threads. It is more like “waiting” a thread to finish, before continues with execution of the code in the calling thread. I have seen people usually do this in following manner:
public class Program { public static void Main() { Thread someThread = new Thread(SomeThreadMethod); // Start the thread execution someThread.Start(); // Put main thread into infinite sleep Thread.Sleep(Timeout.Infinite); // Main thread never resumes! } private static void SomeThreadMethod() { // The thread's code ... } }
Well it might look OK and it works OK but it is somehow “ugly” and you lose control over the main thread continuation. .NETMF provides nice way of doing this:
public class Program { public static void Main() { Thread someThread = new Thread(SomeThreadMethod); // Start the thread execution someThread.Start(); // Tell main tread to wait until someThread finish its execution someThread.Join(); // Main thread code continues ... } private static void SomeThreadMethod() { // The thread's code ... } }
Now that’s better! You still may block the app from exiting: just never return from SomeThreadMethod(). But anytime you decide to change algorithm you can do it easily. Another advantage of Join() method is that you do not have to do event synchronising thus saving yourself writing few more lines of code.
Here also one very quick way just to drop some thread to do something:
public class Program { public static void Main() { new Thread( () => Debug.Print("Hello ...") ) { Priority = ThreadPriority.AboveNormal } .Start(); new Thread( () => { Debug.Print("Line 1"); Debug.Print("Line 2"); }) { Priority = ThreadPriority.Lowest } .Start(); // Main thread code continues ... } private static void SomeThreadMethod() { // The thread's code ... } }