【问题标题】:High CPU when Windows service queue is stored in a databaseWindows 服务队列存储在数据库中时 CPU 高
【发布时间】:2017-02-15 20:30:58
【问题描述】:

我已经使用存储在数据库表中的队列实现了一个 Windows 服务。

我有一个名为MyQueue 的表,该表的每一行都为 Windows 服务指定一个任务。当任务完成时,该行会标有特殊标志,表示该任务已完成。

我的 Windows 服务按以下方式工作:

while(true)
{
     // get the first row from MyQueue that is not yet marked

     // complete the task from the row

     // mark the row as completed
}

这种设计有效,但是当我使用while(true) 时,它会不断向数据库发送请求以检查是否有任何新行,这会导致 CPU 使用率上升超过 60%。

有没有更有效的方法来实现存储在数据库表中的队列?

【问题讨论】:

  • 向 MyQueue 添加行是什么?你不能让它也提醒你的服务吗?

标签: c# service windows-services


【解决方案1】:

你可以使用 SqlTableDependency

【讨论】:

    【解决方案2】:

    当队列中没有数据时,您可以通过在当前线程中添加一些睡眠(根据工作负载)来控制 CPU 使用率。

    while(true)
     {
        // get the first row from MyQueue that is not yet marked
        if(MyQueue.Count == 0)
        {
           System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(1000));
              continue;
        }
    
         // complete the task from the row
    
          // mark the row as completed
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多