Proper use of the IDisposable interface

后端 未结 19 3276
情深已故
情深已故 2020-11-21 04:05

I know from reading the Microsoft documentation that the \"primary\" use of the IDisposable interface is to clean up unmanaged resources.

To me, \"unman

19条回答
  •  独厮守ぢ
    2020-11-21 04:41

    IDisposable is often used to exploit the using statement and take advantage of an easy way to do deterministic cleanup of managed objects.

    public class LoggingContext : IDisposable {
        public Finicky(string name) {
            Log.Write("Entering Log Context {0}", name);
            Log.Indent();
        }
        public void Dispose() {
            Log.Outdent();
        }
    
        public static void Main() {
            Log.Write("Some initial stuff.");
            try {
                using(new LoggingContext()) {
                    Log.Write("Some stuff inside the context.");
                    throw new Exception();
                }
            } catch {
                Log.Write("Man, that was a heavy exception caught from inside a child logging context!");
            } finally {
                Log.Write("Some final stuff.");
            }
        }
    }
    

提交回复
热议问题