mayap
mayap

Reputation: 569

c#: how terminate a background thread in dispose() method?

I have a program which runs a thread. The thread performs processing all the time and it uses some synchronized queue.

The class snapshot is as follows:

public class MyClass:IDisposable
{
    private Thread myThread = new Thread(threadFunc);
    private volatile bool runThread = true;

    public MyClass()
    {
        myThread.Start();
    }

    public Dispose()
    {
        runThread = false;
    }

    private void threadFunc()
    {
        try
        {
           while(runThread){
           queue.Take(); //This method blocks the thread if queue is empty. It uses Monitor class
   //do some processing
           }
        }
        catch(Exception e){...}
    }
    private void otherFunc()
    {
        queue.enqueue(...);//this method is executed by main thread and uses lock while adding element to the queue.
    }
}

When I call Dispose() method, the thread exists threadFunc() method, but after a sec I get an execption from this func "Unable to avaluate expression...", as if the tread was terminated while doing some work. Maybe it has just released from queue.Take() blocking and has no context to run. I know I'm missing something...

How can I solve such problem and terminate the thread from the Dispose method.

Many thanks!!!

Upvotes: 1

Views: 1534

Answers (2)

Brian Gideon
Brian Gideon

Reputation: 48959

Use the overload of Take that accepts a CancellationToken. You can get a reference to a token by using the CancellationTokenSource which also has the Cancel method that you can call from Dispose to unblock the Take method. You can read more cancellation here.

Upvotes: 2

Kell
Kell

Reputation: 3327

Use the poison pill approach: See this thread

Upvotes: 1

Related Questions