I am writing a program that reads data packets from a file, and assigns each packet to a specified pipeline for processing. Each pipeline object has a blocking queue and a filter class. There can be several such pipelines in operation simultaneously.
The blocking queue just collects packets on the input side until it reaches maximum capacity, at which time it blocks the Queue method until the filter Dequeue’s some packets. The blocking queue is a simple class that uses Monitor.Wait() and Monitor.Pulse() for synchronization.
Each filter has a Process() method that is executed on its own dedicated thread. It looks something like this:
public void Process()
{
while (!done)
{
var packet = sourceQueue.Dequeue();
// Perform some filtering operation on packet here
targetQueue.Enqueue(sourceQueue);
// Let other threads do some work
Thread.Sleep(Timespan.Zero);
}
}
What are the possible pitfalls of using the Thread.Sleep() method in this way?
The MSDN documentation stipulates that the use of Thread.Sleep(Timespan.Zero) “indicates that this thread should be suspended to allow other waiting threads to execute,” which is what I want.
But there are blog entries like this one that basically state that using Thread.Sleep is evil. Why? Is this a good use of Thread.Sleep, or is there a better way?
Real programs don’t Sleep().
Your suggestion,
Sleep(0)has an additional problem with allowing only threads with the same priority to run. GenerallySleep(1)is considered a little safer. See Joe Duffy.But in either case your resolution is ~20ms, which could be way too long.
Your loop as stated does a tiny bit of work and then induces a context switch, very wasteful.
It’s a lot better to make the most of a time-slot, so keep working until the Queue blocks you. Blocking is better than sleeping.