When myThread.Start(…) is called, do we have the assurance that the thread is started? The MSDN documentation isn’t really specific about that. It says that the status of is changed to Running.
I am asking because I’ve seen a couple of times the following code. It creates a thread, starts it and then loop until the status become Running. Is that necessary to loop?
Thread t = new Thread(new ParameterizedThreadStart(data));
t.Start(data);
while (t.ThreadState != System.Threading.ThreadState.Running &&
t.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
{
Thread.Sleep(10);
}
Thanks!
If you’re set on not allowing your loop to continue until the thread has “started”, then it will depend on what exactly you mean by “started”. Does that mean that the thread has been created by the OS and signaled to run, but not necessarily that it’s done anything yet? Does that mean that it’s executed one or more operations?
While it’s likely fine, your loop isn’t bulletproof, since it’s theoretically possible that the entire thread executes between the time you call
Startand when you check theThreadState; it’s also not a good idea to check the property directly twice.If you want to stick with checking the state, something like this would/could be more reliable:
However, this is still subject to the possibility of the thread starting, running, then stopping before you even get the chance to check. Yes, you could expand the scope of the
ifstatement to include other states, but I would recommend using aWaitHandleto signal when the thread “starts”.You still have the possiblity of the thread ending before you check, but you’re guaranteed to have that
WaitHandleset once the thread starts. The call toWaitOnewill block indefinitely untilSethas been called on theWaitHandle.