I have one thread responsible for enqueuing and one thread responsible for dequeuing. However, the frequency of the data being enqueued far surpasses the time needed to dequeue + process the data. When I did the following, I ended up with a huge delay in data processing:
public void HandleData()
{
while (true)
{
try
{
if (Queue.Count > 0)
{
Queue.TryDequeue(out item);
ProcessData(item);
}
else
{
Thread.Sleep(10);
}
}
catch (Exception e)
{
//...
}
}
}
Next I tried, processing the data in separate tasks, but this ended up affecting other tasks in the project since this treatment ended up taking up most of the resources allocated to the application and generating a high thread count.
public void HandleData()
{
while (true)
{
try
{
if (Queue.Count > 0)
{
Queue.TryDequeue(out item);
Task.Run(() => ProcessData(item));
}
else
{
Thread.Sleep(10);
}
}
catch (Exception e)
{
//
}
}
}
Next, I tried the following :
public void HandleData()
{
List<Task> taskList = new List<Task>();
while (true)
{
try
{
if (Queue.Count > 0)
{
Queue.TryDequeue(out item);
if (taskList.Count <= 20)
{
Task t = Task.Run(() => ProcessData(item));
taskList.Add(t);
}
else
{
ProcessData(item);
}
}
else
{
Thread.Sleep(10);
}
taskList.RemoveAll(x => x.IsCompleted);
}
catch (Exception e)
{
//...
}
}
}
This seems to have solved the problem, but I wonder if there is a cleaner way to do it? a way to set a maximum concurrent threads number while dequeuing?