views:

257

answers:

5

If I create and start a thread, how does calling Thread.Sleep(x) within that thread affect the ThreadState (if at all)?

Thanks!

+2  A: 

From MSDN

WaitSleepJoin The thread is blocked. This could be the result of calling Thread.Sleep or Thread.Join, of requesting a lock — for example, by calling Monitor.Enter or Monitor.Wait — or of waiting on a thread synchronization object such as ManualResetEvent.

Short answer is: Yes!

Luca Martinetti
+1 Thanks for the link!
Pwninstein
+2  A: 

ThreadState defines a set of all possible execution states for threads. Once a thread is created, it is in at least one of the states until it terminates. Threads created within the common language runtime are initially in the Unstarted state, while external threads that come into the runtime are already in the Running state. An Unstarted thread is transitioned into the Running state by calling Start. Not all combinations of ThreadState values are valid; for example, a thread cannot be in both the Aborted and Unstarted states.

Important: Thread state is only of interest in a few debugging scenarios. Your code should never use thread state to synchronize the activities of threads.

ThreadState: WaitSleepJoin: The thread is blocked as a result of a call to Wait, Sleep, or Join.

From here.

Mitch Wheat
+1, very helpful, thanks. "Your code should never use thread state to synchronize the activities of threads." Could you elaborate just a little on what you mean by that, thanks!!
Pwninstein
@Pwninstein: it means that you should rely on the provided lock mechanisms to implement synchonization, and not by checking a Thread's state.
Mitch Wheat
+1  A: 

It transitions to WaitSleepJoin.

jerryjvl
A: 

I don't want this to come over as a sarcastic answer, as that won't help anyone - so please take this in the spirit that it was intended.

Have you tried creating a simple winform app with buttons to start, stop and sleep a thread and a status area to show the value of thread.ThreadState?

This will answer your question.

If you're going to down vote this at least explain why. All I'm trying to suggest is that people do a bit of experimentation before posting questions. If their experiments don't answer their questions, they can ask here with evidence as to what they've already tried.

ChrisF
+1  A: 

The thread should be put into ThreadState.WaitSleepJoin.

For details, see ThreadState's Documentation, specifically:

WaitSleepJoin: "The thread is blocked. This could be the result of calling Thread..::.Sleep or Thread..::.Join, of requesting a lock — for example, by calling Monitor..::.Enter or Monitor..::.Wait — or of waiting on a thread synchronization object such as ManualResetEvent. "

Reed Copsey