NeddySpaghetti
NeddySpaghetti

Reputation: 13495

Thread.Sleep implementation

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

Answers (3)

Brian Gideon
Brian Gideon

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.
  • A duration parameter = 0 will cause the current thread to yield to another with equal or higher priority.
  • A duration parameter > 0 will cause a context switch and the current thread will remain in a Waiting state for until the specified amount of time has elapsed (approximately).
  • The thread will remain in an alertable state which means it is allowed to process APC methods via QueueUserAPC and will respond to 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

mrjoltcola
mrjoltcola

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

Z .
Z .

Reputation: 12837

Use await Task.Delay() if you want the thread to be reused

Upvotes: 0

Related Questions