Created
September 7, 2015 06:22
-
-
Save sheastrickland/951fcb0e89e68f2c355d to your computer and use it in GitHub Desktop.
Landlord: The Com Destroyer. A simple utility class to wrap those nasty little devils.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment