I’ve never really used threading before in C# where I need to have two threads, as well as the main UI thread. Basically, I have the following.
public void StartTheActions()
{
// Starting thread 1....
Thread t1 = new Thread(new ThreadStart(action1));
t1.Start();
// Now, I want for the main thread (which is calling `StartTheActions` method)
// to wait for `t1` to finish. I've created an event in `action1` for this.
// The I wish `t2` to start...
Thread t2 = new Thread(new ThreadStart(action2));
t2.Start();
}
So, essentially, how can I have a thread wait for another one to finish? What is the best way to do this?
I can see five options available:
1. Thread.Join
As with Mitch’s answer. But this will block your UI thread, however you get a Timeout built in for you.
2. Use a
WaitHandleManualResetEventis aWaitHandleas jrista suggested.One thing to note is if you want to wait for multiple threads:
WaitHandle.WaitAll()won’t work by default, as it needs an MTA thread. You can get around this by marking yourMain()method withMTAThread– however this blocks your message pump and isn’t recommended from what I’ve read.3. Fire an event
See this page by Jon Skeet about events and multi-threading. It’s possible that an event can become unsubcribed between the
ifand theEventName(this,EventArgs.Empty)– it’s happened to me before.(Hopefully these compile, I haven’t tried)
4. Use a delegate
If you do use the _count method, it might be an idea (to be safe) to increment it using
Interlocked.Increment(ref _count)I’d be interested to know the difference between using delegates and events for thread notification, the only difference I know are events are called synchronously.
5. Do it asynchronously instead
The answer to this question has a very clear description of your options with this method.
Delegate/Events on the wrong thread
The event/delegate way of doing things will mean your event handler method is on thread1/thread2 not the main UI thread, so you will need to switch back right at the top of the HandleThreadDone methods: