Yes. I have a complete solution for you.
You should run you thread forever but keep in in wait state until it is awaken for a job to do.
The way to get to such a wait state is using System.
Threading.EvenWaitHandle.WaitOne
. At the call to this method, your thread is switched off by OS and never scheduled back until awaken, so it consumes zero CPU time. The thread can be awaken by a call in the other thread:
System.Threading.Thread.Abort
or
System.Threading.EvenWaitHandle.Set
on the same instance of
EvenWaitHandle
, that should be done when the task is ready. If your
Wait
was called with timeout, the thread can be awaken by the expiration of the timeout as well.
But you don't have to program this manually. You need to use a blocking queue. The elements of the queue could be data sets for you tasks or even delegates (see me reference below).
I provide a generic blocking queue in my Tips/Tricks article:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^]. It is complete with full source code and usage samples (some are nearly ready for your service). Also, pay attention to the alternative on the same page: there is a Framework class doing the same thing in v.4.0. You need to follow the usage I've shown in my samples, though.
—SA