A base implementation of System.IDisposable

Based on this article by Joe Duffy. (Shoutz to Mario Lionello for his collaboration on this.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using System;
using System.Threading;
 
namespace PatternExplorer {
   /// <summary>
   /// Provides a base implementation of <see cref="IDisposable"/>.
   /// </summary>
   /// <remarks>
   /// 
   /// Derived classes that need finalizers should implement the following
   ///  AND be sealed.
   /// 
   ///    /// <summary>
   ///    /// Finalizer.
   ///    /// </summary>
   ///    ~MyClass() {
   ///       Dispose(false);
   ///    }
   /// 
   /// Derived classes that need to protect against access of disposed state
   ///  can use the following example:
   /// 
   ///    /// <summary>
   ///    /// Member accessing potentially disposed state.
   ///    /// </summary>
   ///    public void MyMethod() {
   ///       ThrowIfDisposed();
   ///       // ... 
   ///    }
   /// 
   /// </remarks>
   public abstract class Disposable : IDisposable {
      /// <summary>
      /// "Not Disposed" state.
      /// </summary>
      private const int NOT_DISPOSED = 0;
 
      /// <summary>
      /// "Disposing" state.
      /// </summary>
      private const int DISPOSING = 1;
 
      /// <summary>
      /// "Disposed" state.
      /// </summary>
      private const int DISPOSED = 2;
 
      /// <summary>
      /// A flag to indicate state of disposal.
      /// </summary>
      private int _State;
 
      /// <summary>
      /// Constructor.
      /// </summary>
      protected Disposable() {}
 
      /// <summary>
      /// <c>true</c> if the instance has been disposed; otherwise, <c>false</c>.
      /// </summary>
      public bool IsDisposed {
         get { return Thread.VolatileRead(ref _State) != DISPOSED; }
      }
 
      /// <summary>
      /// Occurs when the instance is being disposed.
      /// </summary>
      public event EventHandler Disposing;
 
      /// <summary>
      /// Occurs when the instance has been disposed.
      /// </summary>
      public event EventHandler Disposed;
 
      /// <summary>
      /// Notifies listeners that the instance is being disposed.
      /// </summary>
      protected virtual void OnDisposing() {
         if( Disposing != null ) {
            Disposing.Invoke(this, EventArgs.Empty);
         }
      }
 
      /// <summary>
      /// Notifies listeners that the instance has been disposed.
      /// </summary>
      protected virtual void OnDisposed() {
         if( Disposed != null ) {
            Disposed.Invoke(this, EventArgs.Empty);
         }
      }
 
      /// <summary>
      /// Performs application-defined tasks associated with freeing,
      ///  releasing, or resetting resources held by the current instance.
      /// </summary>
      public void Dispose() {
         Dispose(true);
      }
 
      /// <summary>
      /// Disposes the instance.
      /// </summary>
      /// <param name="disposing"><c>true</c> to indicate explicit
      ///  cleanup (i.e. <see cref="IDisposable.Dispose"/>()), otherwise
      ///  <c>false</c> (i.e. implicit cleanup from finalizer)</param>
      protected void Dispose( bool disposing ) {
         // if( _State == NOT_DISPOSED ) {
         if( Interlocked.CompareExchange(ref _State, 
                                             DISPOSING, 
                                             NOT_DISPOSED) == NOT_DISPOSED ) {
            // _State = DISPOSING;
 
            if( disposing ) {
               try {
                  OnDisposing();
               } catch {
                  // intentional suppression
               }
               try {
                  DisposeManagedFields();
               } catch {
                  // intentional suppression
               }
               try {
                  RemoveDelegates();
               } catch {
                  // intentional suppression
               }
            }
 
            try {
               ReleaseUnmanagedResources();
            } catch {
               // intentional suppression
            }
 
            Interlocked.Increment(ref _State); // _State = DISPOSED;
 
            if( disposing ) {
               try {
                  GC.SuppressFinalize(this);
               } catch {
                  // intentional suppression
               }
               try {
                  OnDisposed();
               } catch {
                  // intentional suppression
               }
            }
         }
      }
 
      /// <summary>
      /// When overridden in a derived class, this method should dispose
      ///  all <see cref="IDisposable"/> fields.
      /// </summary>
      protected virtual void DisposeManagedFields() {}
 
      /// <summary>
      /// When overridden in a derived class, this method should remove
      ///  all delegate invocations and references.
      /// </summary>
      protected virtual void RemoveDelegates() {}
 
      /// <summary>
      /// When overridden in a derived class, this method should clean up
      ///  any unmanaged resources.
      /// </summary>
      protected virtual void ReleaseUnmanagedResources() {}
 
      /// <summary>
      /// Derived classes may use this method to prevent member access
      ///  on a disposed instance.
      /// </summary>
      protected void ThrowIfDisposed() {
         if( IsDisposed ) {
            throw new ObjectDisposedException(GetType().FullName,
               @"Access to a disposed object is not allowed.");
         }
      }
   }
}

Get the code here.

3 thoughts on “A base implementation of System.IDisposable

  1. Hi Peter-John

    Interesting post and I like the website. Perhaps this is a silly question, but what is the purpose of the Disposable class – i.e. is it for illustration purposes, or should classes derive from it? In the latter case, would it not clash with OO design concepts in many cases – as you can’t have multiple inheritance, you’re basically stating that the defining feature of the derived class is that it’s disposable?

    Thanks

    • Hi Brendon, thanks for the valuable question!

      Yes, the class is intended to be inherited (as will be illustrated in my follow-up post). But, in an of itself that should not clash with any OO design concepts, and neither does any base class determine the defining feature of its derived classes. When we talk OO, we say that derived classes “specialize” the type of the base class, that they are “more specialized” than the base, or that the base class is “more general” or “less specific” than the derived classes. As such, the base class can at most determine some characteristics of the derived class. There is in principle no limit on how the derived class can extend the base.

      Nevertheless your alarm is quite rightly placed. In this particular case one has to consider the derived class in detail, before deciding to inherit from Disposable. If there is contention in that the class may also rightly derive from a different base, then one has done well to pause.

      If Disposable was at all difficult to implement or widely used, I’m sure the framework would have had its own implementation. But, while there are no doubt valid reasons for the framework to only provide the IDisposable interface, that does not imply that we MUST always implement the interface from scratch.

      To conclude (and hopefully satisfy your query) – this kind of abstract base class is probably not something that you’d ship as part of a public library, but can be a very useful addition to an internal framework, where you are at once the publisher and consumer of the class. In such a scenario you are free to both inherit the base functionality on the occasions where you have classes that are in themselves of a fairly primitive nature (does not inherit base functionality – ironically these are usually the ones where you’d want IDisposable functionality), or alternatively simply use the code as a template for the manual implementation of the IDisposable interface (i.e. for illustration purposes).

      Just an afterthought about the possible intent of your question… I would say classes “may” derive from it, not that classes “should” derive from it (i.e. don’t simply make all classes disposable). Also, classes deriving from it (and for that matter any classes implementing IDisposable) shouldn’t necessarily add a finalizer unless it’s specifically required by the state or owned objects of that class. Finally, when a class does implement IDisposable or inherit this base, if it defines a finalizer it should be sealed, as further consumers will not necessarily be aware of the finalizer and may add additional finalizers into the hierarchy, which would start to make the derived object very expensive to use.

  2. Thanks for taking the time to provide such a detailed response.

    Yeah, “may derive” was the correct interpretation. Good explanation – it’s quite clear now.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">