微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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使用率保持很高.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐