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
332 views
in Technique[技术] by (71.8m points)

c# - Thread.Sleep or Thread.Yield

I have a method that uses a background worker to poll a DLL for a status looking something like this:

var timeout = DateTime.Now.AddSeconds(3);
while (System.Status != Status.Complete  // our status is not complete
       && DateTime.Now < timeout         // have not timed out
       && !_Worker.CancellationPending)  // backgroundworker has not been canceled
{
    //Thread.Yield();
    //Thread.SpinWait(1);
    //Thread.Sleep(1);
}

When looking at my CPU %, yield() and spinwait() cause my app to shoot up to 50% on my PC. With Sleep(1) my CPU % stays down at 6%. I have been told that that I should choose Thread.Yield(), however the spikes in CPU % bother me. What is best practice for something like this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Thread.Yield will interrupt the current thread to allow other threads to do work. However, if they do not have any work to do, your thread will soon be rescheduled and will continue to poll, thus 100% utilization of 1 core.

Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

Thread.Sleep will schedule your thread to run again after the sleep time expires, thus much lower CPU utilization.

Blocks the current thread for the specified number of milliseconds.

Given the choice between the two, Thread.Sleep is better suited for your task. However, I agree with the comment from @Bryan that a Threading.Timer makes for a more elegant solution.


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

...