HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is it ok to use Thread.Sleep and Thread.Interrupt for pausing and resuming Thread like this?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisinterruptsleepresuminglikethreadforpausinganduse

Problem

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 be static because the Thread have to be interrupted by different Threads)

Solution

This is pretty bad.

Instead why not use BlockingCollection. Then the loop will be:

try
{
    while(true)
    {
        doSomethingWith(queue.Take());
    }
}
catch(InvalidOperationException e)
{
    // ignore and cleanup
}


And to stop the thread you need to call CompleteAdding() on the queue.

Code Snippets

try
{
    while(true)
    {
        doSomethingWith(queue.Take());
    }
}
catch(InvalidOperationException e)
{
    // ignore and cleanup
}

Context

StackExchange Code Review Q#82374, answer score: 7

Revisions (0)

No revisions yet.