How to implement a one-time template in a class that inherits from another one-time class?

I often used a one-time template in simple classes that referenced a small amount of resources, but I never had to implement this template for a class that inherits from another one-time class, and I'm starting to get a little confused about how to free up whole resources.

I start with a small code example:

public class Tracer : IDisposable
{
    bool disposed;
    FileStream fileStream;

    public Tracer()
    {
        //Some fileStream initialization
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                } 
            }

            disposed = true; 
        }
    }
}

public class ServiceWrapper : Tracer
{
    bool disposed;
    ServiceHost serviceHost;

    //Some properties

    public ServiceWrapper ()
    {
        //Some serviceHost initialization
    }

    //protected override void Dispose(bool disposing)
    //{
    //    if (!disposed)
    //    {
    //        if (disposing)
    //        {
    //            if (serviceHost != null)
    //            {
    //                serviceHost.Close();
    //            } 
    //        }

    //        disposed = true;
    //    }
    //}
}

My real question is: how to implement a one-time template inside my ServiceWrapper class to make sure that when I delete its instance, it will have resources in both the inherited and the base class?

Thank.

+3
source share
4 answers

, :

  • Dispose (bool disposing), , Dispose (bool disposing). , , .

  • , Dispose (bool disposing) . , . , .

+3

, -, , GC.Suppressfinalizer. , , .

, IDispose .

public class Disposable : IDisposable
{
    private object _lock = new object();

    ~Disposable()
    {
        try
        {
            Dispose(false);
        }
        catch
        {

        }
    }

    protected void ThrowIfDisposed()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException(GetType().FullName);
        }
    }

    public bool IsDisposed { get; private set; }

    protected virtual void Dispose(bool disposing)
    {

    }

    public void Dispose()
    {
        lock (_lock)
        {
            if (!IsDisposed)
            {
                Dispose(true);
                IsDisposed = true;
                GC.SuppressFinalize(this);
            }
        }
    }
}
+2

The inherited class, ServiceWrapper, inherits from the class that implements IDisposable, so SericeWrapper also implements IDisposable. For proof, a new instance of ServiceWrapper. You will find (with intellisense) that it also has a Dispose () method.

0
source

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


All Articles