Search code examples
c#.netmultithreadingtask-parallel-libraryblocking

Thread blocking based on boolean value


I have a service which processes data from a queue:

while (true)
{
    if(!HaltProcessing)
    { 
        var messages = receivedQueue.GetMessages(MessageGetLimit);

        if (messages.Count() > 0)
        {
            ProcessQueueMessages(messages);
        }
        else
        {
            Task.Delay(PollingInterval);
        }
    }
}

There is a HaltProcessing property which, when set to true, pauses the processing of queue items. I do this through the if statement as seen above.

Is there a better way to block the thread when HaltProcessing is true and unblock when false?


Solution

  • Yes, you can use "WaitHandles".

    AutoResetEvent or ManualRestEvent to achieve it.

    private ManualRestEvent signal = new ManualRestEvent(false);//or true based on your req
    //Setting true is to allow processing and false is to halt the processing
    
    while (true)
    {
        signal.WaitOne();
        var messages = receivedQueue.GetMessages(MessageGetLimit);
    
        if (messages.Count() > 0)
        {
            ProcessQueueMessages(messages);
        }
        else
        {
            Task.Delay(PollingInterval);
        }
    }
    
    bool SetHaltProcessing(bool value)
    {
        if(value)
           signal.Reset();
        else
           signal.Set();
    }
    

    Use case

    SetHaltProcessing(true);//To halt the processing
    SetHaltProcessing(false);//To start the processing