【问题标题】:Proper way to throttle created tasks within a while loop在 while 循环中限制创建的任务的正确方法
【发布时间】:2022-01-10 05:53:52
【问题描述】:

我有一个等待消息到达队列的侦听器。我想限制任务的数量,以便对于队列中的每 1000 条消息,我需要等到它们完成后再处理下一组消息。原因是 ProcessMessage 代码调用了 WCF 服务,而这似乎会因为同时调用太多并发调用而超载。

我想知道这是实现这种节流的最佳方式吗?下面的代码看起来有点hacky。

var isEmpty = false;
var maxThreads = 1000;
var currentThreadCount = 0;
List<Task> taskList = new List<Task>();
while(!isEmpty)
{
  var message = GetMessageFromServer();
  if(!String.IsNullorEmpty(message))
  {
     isEmpty = true;
  }
  else
  {
    if(currentThreadCount == maxThreads)
     {
       task.WaitAll(tasksList.ToArray());
       currentThreadCount = 0;
     }
    else
    {
    taskList.Add(Task.Run(() => ProcessMessage(message)));
    }
  }    
}

【问题讨论】:

标签: c# multithreading concurrency task task-parallel-library


【解决方案1】:

假设您对 ProcessMessage 的结果感兴趣,我建议您考虑使用 Channels (cf.)。

相对于您的解决方案,这可以改进的一点是,您可以确保工作量一致,并且在达到 1000 时不会停止并等待所有任务完成。

【讨论】:

  • 太好了。我会和这个一起去的。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 2014-11-06
  • 2019-09-29
  • 1970-01-01
  • 2018-09-01
  • 2016-02-14
  • 1970-01-01
相关资源
最近更新 更多