Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

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

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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...