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

前端 未结 3 1236
遥遥无期
遥遥无期 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:43

    Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

    Framework 4.0’s new Thread.Yield() method does the same thing — except that it relinquishes only to threads running on the same processor.

    source

    0 讨论(0)
  • 2020-12-14 08:46

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题