Finalizers and Dispose

后端 未结 6 1566
失恋的感觉
失恋的感觉 2021-01-01 06:04

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

6条回答
  •  一整个雨季
    2021-01-01 06:58

    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.

提交回复
热议问题