Search code examples
c#multithreadingblockingcollection

C# Correctly aborting a always running thread with a BlockingCollection


I am running a thread that has a

while(isRunning) 
{ 
    blockingCollection.Take()
}

First I am setting isRunning to false. Then I call thread.Interrupt which stops the blockingCollection from waiting for new items. After that I call my Dispose Method for the class running the Thread inside the catch block.

Is that the best/correct way to do this?


Solution

  • A BlockingCollection has a CompleteAdding() method and full support for Cancellation.

    while(isRunning && ! blockingCollection.IsCompleted) 
    { 
       isRunning = blockingCollection.TryTake(out someThing, -1, cancelToken);
    }
    

    This way you can and should let the Thread end normally, always the better option.