Difference between Thread.Sleep(0) and Thread.Yield()

前端 未结 3 1237
遥遥无期
遥遥无期 2020-12-14 08:00

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. Previous

3条回答
  •  北海茫月
    2020-12-14 08:47

    As explained by Eric Lippert in his Coverity blog post “How does locking work in C#?” while demonstrating how to implement locking—

    The .NET Framework gives you multiple tools you could use to build a more sophisticated waiting strategy: Thread.SpinWait puts the processor into a tight loop allowing you to wait a few nanoseconds or microseconds without ceding control to another thread. Thread.Sleep(0) cedes control to any ready thread of equal priority or keeps going on the current thread if there is none. Thread.Yield cedes control to any ready thread associated with the current processor. And as we’ve seen, Thread.Sleep(1) cedes control to any ready thread of the operating system’s choice. By carefully choosing a mix of these calls and doing performance testing in realistic conditions you could build a high-performance implementation, and of course this is what the CLR team has actually done.

提交回复
热议问题