我有一个方法,使用后台工作程序轮询DLL的状态,如下所示:
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);
}
Run Code Online (Sandbox Code Playgroud)
当看着我的CPU%,yield()并spinwait()导致我的应用程序来拍摄高达50%,我的电脑上.随着Sleep(1)我的CPU%,6%,保持了下来.我被告知我应该选择Thread.Yield(),但是CPU%的高峰会让我感到困扰.什么是这样的最佳做法?
我正在实现一种通信算法来定期和非常快速地发送信息,即包之间的1ms.我有一个使用Tasks发送包的功能版本.这是我的代码示例:
private void Work()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (!cancellationTokenSource.Token.IsCancellationRequested)
{
if (!Pack.PeriodicOn)
cancellationTokenSource.Cancel();
// Time used to send the packs before the interval time
double tolerance = Pack.Interval * 0.2F;
// In case of interval bigger than 25ms send pasks only 5ms before
if (tolerance > 5) tolerance = 5;
TimeSpan timeSpan = stopwatch.Elapsed;
// The waiting time is controlled by the condition below, if the condition is false, the while loop continues execution
// Send …Run Code Online (Sandbox Code Playgroud)