Skip to content

Instantly share code, notes, and snippets.

@szymczakk
Created December 12, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szymczakk/04e490c47d7211effc9e2d6aa6940853 to your computer and use it in GitHub Desktop.
Save szymczakk/04e490c47d7211effc9e2d6aa6940853 to your computer and use it in GitHub Desktop.
Disposable order question
public class NextDisposableResource: DisposableResource
{
private DisposableResource disposableResource;
protected override void Dispose(bool disposing)
{
disposableResource.Dispose();
base.Dispose(disposing);
}
}
public class OtherDisposableResource: DisposableResource
{
private DisposableResource disposableResource;
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
disposableResource.Dispose();
}
}
@kkokosa
Copy link

kkokosa commented Dec 13, 2017

Klasa NextDisposableResource staje się właścicielem disposableResource więc niejako od nowa powinna zaimplementować w sobie IDisposable pattern:

public class NextDisposableResource : DisposableResource 
{
    private bool disposed;
    private DisposableResource disposableResource;
    
    protected override void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                disposableResource?.Dispose();			
            }
            disposed = true;
        }
        base.Dispose(disposing);
    }
}

Polecam świetny artykuł http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/ zwłaszcza fragmenty (z dalszymi adnotacjami):

Do create or override the protected virtual void Dispose(bool disposing) method to encapsulate all of your cleanup logic. All cleanup should occur in this method, predicated—if necessary—by the disposing argument. The argument’s value will equal false if being invoked from inside a finalizer, which should be used to ensure any code running from a finalizer is careful to follow the Finalize guidelines detailed in the next section.

oraz dotyczący kolejności:

Do make a call to your base class’s Dispose(bool disposing) method (if available) as the last operation in your Dispose(bool) implementation. Make sure to preserve the value of the disposing argument by passing the same value that your method received. This makes sure that base classes are given a chance to clean up of resources, but not before your cleanup code executes (which could rely on their presence).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment