I need to observe a ConcurrentQueue
, but to minimize the resources I want to pause the Thread if the Queue is empty and resume it from another Thread if there is a new Entry in the Queue. I implemented a pausing and an resuming of a thread like this:
My Worker, where the DoWork()
method is called in a new Thread, looks like this:
public static class Worker
{
public static bool Running = true;
public static void DoWork()
{
while (Running)
{
try
{
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException)
{
DoActualWork();
}
}
}
private static void DoActualWork()
{
//Do something
}
}
I start the thread like this:
Thread workerThread = new Thread(Worker.DoWork);
workerThread.Start();
I interrupt the Thread like this:
workerThread.Interrupt();
I stop the Thread like this:
Worker.Running = false;
Everything is working as expected but I'm not sure if this is how it should be implemented.
- Is this best practice?
- What can go wrong?
- Is there a problem with the static
class
and the members? (It have to bestatic
because the Thread have to be interrupted by different Threads)
workerThread.Running = false;
do you really meanWorker.Running = false
? \$\endgroup\$