相关疑难解决方法(0)

Thread.Sleep或Thread.Yield

我有一个方法,使用后台工作程序轮询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%的高峰会让我感到困扰.什么是这样的最佳做法?

c# multithreading sleep yield

26
推荐指数
1
解决办法
2万
查看次数

如何在没有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)

.net c# multithreading task winforms

8
推荐指数
1
解决办法
1010
查看次数

标签 统计

c# ×2

multithreading ×2

.net ×1

sleep ×1

task ×1

winforms ×1

yield ×1