Skip to content

Instantly share code, notes, and snippets.

@sheastrickland
Created September 7, 2015 06:22

Revisions

  1. sheastrickland created this gist Sep 7, 2015.
    59 changes: 59 additions & 0 deletions Landlord.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    using System;
    using System.Runtime.InteropServices;

    namespace Things
    {
    public static class LandLordExtensions
    {
    public static LandLord<TWrapped> AsDisposable<TWrapped>(this TWrapped tenant)
    {
    return new LandLord<TWrapped>(tenant);
    }
    }

    public class LandLord<TWrapped> : IDisposable
    {
    public TWrapped Tenant { get; private set; }
    private bool _disposed;

    public LandLord(TWrapped tenant)
    {
    _disposed = false;
    Tenant = tenant;
    }

    protected virtual void Evict(bool byManagement)
    {
    try
    {
    if (_disposed) return;

    if (byManagement)
    {
    using (Tenant as IDisposable){}
    }

    if (Tenant != null && Marshal.IsComObject(Tenant))
    {
    Marshal.ReleaseComObject(Tenant);
    Tenant = default(TWrapped);
    }
    }
    finally
    {
    _disposed = true;
    }
    }

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

    ~LandLord()
    {
    Evict(byManagement: false);
    }
    }
    }