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.

Intro to fluency with TDD

Info

Breakout Session :: 300 (Advanced) :: Developer Practices

“In this demo-filled session, you’ll learn the why, what, where, when and how of working with test-driven development using the tools provided in Visual Studio 2010. In addition to seeing ‘testing-in-action’, you’ll learn about when to use what kind of test. You’ll learn both about using TDD with new code and in legacy situations. Code better and discover features in Visual Studio, such as code coverage and more that will help you to be more productive.”

Highlights

The session centered around fluency in TDD, and the requirement to keep your test code of production quality (i.e. refactor where necessary, etc.) – it also introduced the “Approvals” library, as an alternative to having to assert very granular bits of state.

The testing cycle suggested is: Whiteboard (Requirement), English (Translation), Code (Implementation), Test (Regression) and Result (Verification) and aims to promote the notion of “Intentional Code”.

Links

Using Tests to drive the entire SDLC

Info

Breakout Session :: 300 (Advanced) :: Developer Practices

“Given that you want to deliver high quality code, when you drive your entire software development lifecycle with tests – you will dramatically improve overall quality. Microsoft’s introduction of Visual Studio 2010 and Microsoft Test Manager provides very powerful tools we can use to begin with tests. In this presentation we specify an entire system with tests. We begin with tests to ensure the business value of an application is testable and we know when we’re done. Using those tests, we clarify the requirements using acceptance criteria expressed as test cases. Finally, we decompose the requirements to specific testable behaviours that will drive our unit tests. Armed with the complete understanding of the application, we begin to work upwards again. We automate the unit tests to ensure our code is tested. Then, as our code begins to take shape, we automate the functional tests to ensure our requirements are met – and stay met as our code continues to evolve. Finally, we automate the system and integration tests to prove to our customers that we have met the end-to-end vision of the application. The final demonstration shows the integration of all tests running during an automated nightly build.”

Video