LoginSignup
3
3

More than 5 years have passed since last update.

Disposed

Last updated at Posted at 2013-10-02

誰もが作るであろう何か

Disposed

abstract class Disposable : IDisposable
{
    ~Disposable()
    {
        Dispose( false);
    }
    public void Dispose()
    {
        Dispose( true);
        GC.SuppressFinalize(this );
    }

    public bool Disposed
    {
        get
        {
            return disposed;
        }
    }

    private bool disposed = false;

    private void Dispose(bool disposing)
    {
        if (disposed)
        {
            return;
        }

        if (disposing)
        {
            OnDisposeManaged();
        }

        OnDisposeUnmanaged();

        disposed = true;
    }

    virtual protected void OnDisposeManaged()
    {
        if (DisposeManagedAction != null )
        {
            DisposeManagedAction();
        }
    }

    virtual protected void OnDisposeUnmanaged()
    {
        if (DisposeUnmanagedAction != null )
        {
            DisposeUnmanagedAction();
        }
    }

    Action DisposeManagedAction { get ; set; }
    Action DisposeUnmanagedAction { get ; set; }
}

使用例 1

普通に継承して使う

class HeapPtr : Disposable
{
    protected override void OnDisposeUnmanaged()
    {
        if (ptr != IntPtr .Zero)
        {
            Marshal.FreeCoTaskMem(ptr);
            ptr = IntPtr.Zero;
        }
    }

    IntPtr ptr;
    public static implicit operator IntPtr (HeapPtr p)
    {
        if (p.Disposed)
            throw new ObjectDisposedException( "p");

        return p.ptr;
    }

    public HeapPtr(int cb)
    {
        ptr = Marshal.AllocCoTaskMem(cb);
        Length = cb;
    }

    public HeapPtr(byte [] buf)
    {
        if (buf == null )
        {
            Length = 0;
            ptr = IntPtr.Zero;
        }
        else
        {
            Length = buf.Length;
            ptr = Marshal.AllocCoTaskMem(Length);
        }

        Marshal.Copy(buf, 0, ptr, Length);
    }

    public int Length { get; private set ; }
}

使用例 2

ラムダ式

using (var d = new Disposed {
    DisposeManagedAction = () => { ... }    
    DisposeUnmanagedAction = () => { ... }    
}) {
    ....
}

こっちのは、記述してみたってだけの未テストなのであしからず。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3