views:

262

answers:

1

As Java has had Sleep and Yield from long ago, I've found answers for that platform, but not for .Net

.Net 4 includes the new Thread.Yield() static method. Previously the common way to hand over the CPU to other process was Thread.Sleep(0).

Apart from Thread.Yield() returning a boolean, are there other performance, OS internals differences?

For example, I'm not sure if Thread.Sleep(0) checks if other thread is ready to run before changing the current Thread to waiting state... if that's not the case, when no other threads are ready, Thread.Sleep(0) would seem rather worse that Thread.Yield().

+2  A: 

According to the MSDN,

When using Sleep(0) The thread will not be scheduled for execution by the operating system for the amount of time specified.

With using Yield() The rest of the thread's current time slice is yielded. The operating system schedules the calling thread for another time slice, according to its priority and the status of other threads that are available to run.

So there's a minor difference in that. Thread.sleep will put a Thread into SLEEP mode with a recommendation that it stay there for the given number of milliseconds Thread.yield will put it into WAIT mode so it may run again straight away, or a higher process thread might step in.

Rhapsody
I think there's not a SLEEP state either at the CLR or the OS level, only WAITING and READY states. I think a Yield could move directly to READY, while a Sleep(n>0) would move to WAITING and once the interval is gone, would move it to READY.I think Sleep(0) could directly move to WAITING, without going through the SLEEP state.
Xose Lluis