I know it is a race condition since the output is different each time I run the code.
This is common with multithreading, and not necessarily due to a race condition (at least not a bad one). Order processing in multithreaded scenarios tends to not be deterministic - which would likely change the output.
That being said, with BlockingCollection<T>
, it's typically easier to write your consumers as:
public void HandleCalls()
{
foreach(var item in incommingCalls.GetConsumingEnumerable())
{
//do something with the call
}
}
This will handle all of the synchronization and checking for you, for any number of consumers on the BlockingCollection<T>
.
Edit: If you need to control the scheduling, and implement some form of Round-Robin Scheduling, you may want to take a look at the Parallel Extension Extras within the samples for the TPL. They provide a RoundRobinTaskScheduler
which can be used to schedule Task<T>
instances which work in a predictable manner.