c# – 继续运行方法的最佳方法是什么

我必须继续运行24×7的方法.基本上
应用程序应该通过使用某个线程每秒处理40个数据.
我可以使用while或递归调用相同的方法.但在这两个过程中
cpu使用率过高几乎95-100%.我不能使用计时器,因为
然后处理线程无法正常工作.根据提供的解决方
许多人说话时使用线程睡眠.但如果我使用线程睡眠
然后它在每次迭代中都会出现延迟.我正在使用c#4.0.

我的问题:有没有更好的解决方案来减少cpu使用?

主要方法

static void Main(string[] args)
     {
    while(true)
    {
      processData();
      Thread.sleep(1000);
    // here i use a 1 second sleep just for give a breath of cpu.
    //But this one second sleep make me delay for enter data processing.
    // I am looking for a better solution that no sleep time will use and cpu usages will getting low.
    }
     }

//Method should run always

static string processData()
{
  {
// Open and close threads  to process the data in every second.
  }

 // processData(); // it can be used for recursive method calling
}

解决方法

but if i use thread sleep then it getting delay in every iteration. i am using c# 4.0.

您可以使用Thread.Sleep(0),表示:

that this thread should be suspended to allow other waiting threads to execute.

static void Main(string[] args)
{
  while(true)
  {
    processData();
    Thread.sleep(0);
  }
}

这将允许线程放弃对其他线程的一些处理,防止它使用100%的cpu,但仍然允许它以接近全速运行.

请注意,使用任何延迟虽然会降低整体cpu使用率,但会降低总吞吐量.最大化吞吐量的唯一方法是允许它不停旋转,这当然会使cpu使用率保持很高.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...