0

I have a listener that waits for messages to arrive in a queue. I want to throttle the amount of tasks so that for every 1000 messages in queue I need to wait until they complete before processing the next set of messages. The reason for this is the ProcessMessage code calls a WCF service and that seems to get overloaded with too many concurrent calls at once.

I want to know is this the best way to achieve thisthrottling? This code below looks a bit 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)));
    }
  }    
}
Terrance Jackson
  • 606
  • 3
  • 13
  • 40
  • 1
    Is this helpful? [How to limit the amount of concurrent async I/O operations?](https://stackoverflow.com/questions/10806951/how-to-limit-the-amount-of-concurrent-async-i-o-operations) – Theodor Zoulias Jan 09 '22 at 16:42
  • It'd be great if you posted real code. The code in your question has too many syntax errors to be real. – Enigmativity Jan 09 '22 at 23:41

1 Answers1

0

Assuming that you are interested in the result of ProcessMessage I would suggest considering the use of Channels (cf.).

What this could improve with respect to your solution is that you could ensure a consistent amount of work and not stopping when 1000 is reached and waiting until all tasks are finished.

Clemens
  • 588
  • 6
  • 9