Help me figure out the Dispose () implementation code from MSDN

following code from MSDN: Identifiable Template

protected virtual void Dispose(bool disposing)
    {
        // If you need thread safety, use a lock around these 
        // operations, as well as in your methods that use the resource.
        if (!_disposed)
        {
            if (disposing) {
                if (_resource != null)
                    _resource.Dispose();
                    Console.WriteLine("Object disposed.");
            }

            // Indicate that the instance has been disposed.
            _resource = null;
            _disposed = true;   
        }
    }

why the following statement:

 _resource = null;  
_disposed = true; 

not enclosed in an if (disposing) block of an operator?

for me I would probably write like this:

if (disposing) {
       if (_resource != null) {
            _resource.Dispose();
            _resource = null;
            _disposed = true;
           }
         Console.WriteLine("Object disposed.");
   }

Is there something wrong with my version?

+3
source share
5 answers

The template designated by MSDN is the only correct way to implement IDisposable, since it takes into account the final development. You need to carefully study the implementation of IDisposable:

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

This calls your dispose method, indicating that it really destroys and undoes further refinement.

It is not possible to call any other object during finalization, so you want to set:

 _resource = null;  
_disposed = true; 

.

IDisposable MSDN.

+1

Dispose() , . , _resource NULL, .

_resource = null;

, .

+1

;)

, _resource = null - , , . , ;) .

_disposed = true, , , _resource. , _resource , Console.WriteLine. , _resource , - , , , dispose .

if (disposing) {
if (_resource != null) {
_resource.Dispose();
_resource = null;
}
_disposed = true;
Console.WriteLine("Object disposed.");
}

.

+1

Dispose(bool) Dispose(), Finalizer ( ~ Class in #). , . _resource , Dispose(bool) Dispose(), " " ( , )

+1

, , MSDN

, , , , Dispose (bool) false Finalizer. , Finalizer , . , Finalizer.

I wrote an improved version of the IDisposable template on my blog - How do you implement the IDisposable template correctly? . You will find that my intended implementation of this template is slightly different from what is published on MSDN. IMHO, this is not enough. You must agree that a large number of samples and examples posted on MSDN are “hacked” and do not do what they should do in the “real world”.

+1
source

Source: https://habr.com/ru/post/1735893/


All Articles