Reputation: 13495
I was curious as to how Thread.Sleep
was implemented. I had a look with Reflector for the implementation of Thread.Sleep
. It calls the following function:
[MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
private static extern void SleepInternal(int millisecondsTimeout);
Does anyone know where that is defined? I am aware of other alternatives, such as Task.Delay. But was curious as to the actual implementation details.
Upvotes: 1
Views: 884
Reputation: 48949
Joe Duffy's book Concurrent Programming provides all of the details you need. But to summarize:
Thread.Sleep
behaves similar to the Win API function SleepEx.Thread.Interrupt
calls.I recommend poking through the SSCLI code for a more complete understanding of how it is implemented.
Regarding your question about not being able to reuse the thread for other work...I am a bit confused. Thread.Sleep
is a voluntary suspension so you (the programmer) told the thread not to do any more work. And like I mentioned above the thread is said to be alertable so you could actually interrupt it or even force it to do work via APC methods.
Refer to this question for more information about getting .NET threads to run APCs while Thread.Sleep
is still pending.
Upvotes: 4
Reputation: 20842
Thread.Sleep()
when called by a system thread (a real thread, not a user-thread) is a call that hooks into the OS kernel scheduling internals, similar to process sleep. It puts the execution context (that is visible at the kernel process level) into a "sleep" wait state so it consumes no CPU until it wakes up. It isn't a busy wait.
If you want it to be awake and/or doing other things, use some other mechanism besides Thread.Sleep()
.
Upvotes: 2