Phreak87 / LeptonicaSharp

Full featured wrapper for leptonica 1.77.0
Other
8 stars 5 forks source link

Use DisposableBase #59

Closed fdncred closed 5 years ago

fdncred commented 5 years ago

The current implementation of Dispose does not follow the Disposable pattern. Using something like this and deriving all disposable classes from it would be better.

using System;
using System.Diagnostics;

namespace Leptonica
{
    public abstract class DisposableBase : IDisposable
    {
        static readonly TraceSource trace = new TraceSource("Leptonica");

        protected DisposableBase()
        {
            IsDisposed = false;
        }

        ~DisposableBase()
        {
            Dispose(false);
            trace.TraceEvent(TraceEventType.Warning, 0, "{0} was not disposed off.", this);
        }

        public void Dispose()
        {
            Dispose(true);

            IsDisposed = true;
            GC.SuppressFinalize(this);

            if (Disposed != null)
            {
                Disposed(this, EventArgs.Empty);
            }
        }

        public bool IsDisposed { get; private set; }

        public event EventHandler<EventArgs> Disposed;

        protected virtual void VerifyNotDisposed()
        {
            if (IsDisposed) throw new ObjectDisposedException(ToString());
        }

        protected abstract void Dispose(bool disposing);
    }
}
Phreak87 commented 5 years ago

im not happy with this iDisposable method because there are a few parts i simply dont like and need. I dont like tracing and raiseevents on dispose. The IsDisposed Boolean is also not needed because the IntPtr is set to null in this case and you can see it this way.

fdncred commented 5 years ago

The point here was to write a proper disposable class to derive from that follows the Dispose pattern. There is a pattern for a reason. https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose