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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…