I\'ve got a class named BackgroundWorker
that has a thread constantly running. To turn this thread off, an instance variable named stop
to needs to
First off, a severe warning. Don't use a finalizer like you are. You are setting yourself up for some very bad effects if you take locks within a finalizer. Short story is don't do it. Now to the original question.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Force the background thread to exit.
///
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (this.locker)
{
this.stop = true;
}
}
}
~BackgroundWorker()
{
Dispose(false);
}
The only reason to have a finalizer at all is to allow sub-classes to extend and release unmanaged resources. If you don't have subclasses then seal your class and drop the finalizer completely.