Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a thread to actually start in c#

I need to start a thread, but continue just after the thread is actually running. Now my code looks like:

        splashthread.IsBackground = false;
        splashthread.Start();
        Thread.Sleep(100); // Wait for the thread to start

I'm not fond of these voodoo sleeps (to say the least), so I'm looking for more nifty way of doing the above.

Any ideas?

like image 722
Guy L Avatar asked Oct 08 '11 23:10

Guy L


2 Answers

Something like this:

var splashStart = new ManualResetEvent(false);

var splashthread = new Thread(
  () =>
  {
     splashStart.Set();
     // Your thread code here...
  });

splashthread.Start();
splashStart.WaitOne();

Don't forget to Dipose splashStart or if it's appropriate in your code use a using block.

Edit: Didn't confirm the original code in the IDE. Changed Wait to WaitOne() as per comment below.

like image 53
Ilian Avatar answered Oct 26 '22 21:10

Ilian


Why do you care when the other thread starts? You well may be interested in knowing when the new thread has reached some particular milestone, and you could use any number of synchronization primitives to deal with that (in addition to events, if the new thread is going to be initializing something visible to the constructing thread, you could use a monitor lock with Monitor.Wait/Monitor.Pulse. Monitor locks are lightweight, but require a little care.

In particular, the thread which is going to wait for the other thread must check within a synclock whether the object has been initialized, before it does Monitor.Wait. Otherwise it's possible that the new thread might perform its Monitor.Pulse before the main thread has reached its Monitor.Wait. Adding the object-initialized check would prevent that scenario. If the new thread hasn't initialized the object before the launcher thread entered the synclock to check and wait, it won't be able to perform the Pulse until after the launcher thread gives up its lock via Monitor.Wait. If the new thread has initialized the object before the launcher thread entered the synclock, the launcher thread will see that and not wait at all.

like image 22
supercat Avatar answered Oct 26 '22 21:10

supercat