Skip to content

Instantly share code, notes, and snippets.

@jkff
Created October 15, 2011 19:03
Show Gist options
  • Save jkff/1289989 to your computer and use it in GitHub Desktop.
Save jkff/1289989 to your computer and use it in GitHub Desktop.
C# autodispose from constructor
public class Guard : IDisposable
{
private List<IDisposable> toDispose = new List<IDisposable>();
public void Add(IDisposable d) { toDispose.Add(d); }
public void Dispose() { foreach(var x in toDispose) x.Dispose(); }
public void Discharge() { toDispose.Clear(); }
public static void Do(Action<Guard> a)
{
using(var g = new Guard()) { a(g); g.Discharge(); }
}
public static T Do<T>(Func<Guard,T> a) { /* analogously */ }
}
public static class DisposeExtensions
{
public static T RegisterForDispose<T>(this T x, Guard g) where T : IDisposable
{
g.Add(x);
return x;
}
}
public class Foo
{
public Foo(...)
{
Guard.Do(g =>
{
this.foo = new SomeResource().RegisterForDispose(g)
.GetDerivedResource().RegisterForDispose(g)
.GetAnotherDerived().RegisterForDispose(g); // None of the chain will leak.
this.bar = ...;
...
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment