Hi,
I have some utility class with worker thread with simple exit condition. I use this class in my application. Worker thread is created and started in class constructor.
class MyClass
{
Thread _thread;
// unrelevant details are omitted
void WorkerThreadRoutine
{
while(_running)
{
// do some useful background work here
}
}
}
My question is WHEN do I have to set _running=false. In C++ with deterministic resource deallocation life is easy - I use object destructors and don't care.
I would write something like
~MyClass()
{
_running = false;
}
In C# there no destructors in C++ sense. Do I have to write some Dispose() function here and use IDisposable? I can of course provide a Stop() function. But when do I have to call it? Is there a way to automatically have my Stop function called?
What is right pattern here? I have lots of MyClass intances across my application.
Right now my application hangs on exit.