Created
          October 15, 2011 19:03 
        
      - 
      
- 
        Save jkff/1289989 to your computer and use it in GitHub Desktop. 
    C# autodispose from constructor
  
        
  
    
      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
    
  
  
    
  | 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