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

Async Calls in Silverlight and WPF Clients

Info

Breakout Session :: 400 (Expert) :: Developer Tools, Languages and Frameworks

“Whenever doing blocking tasks, particularly service calls in a Silverlight or Windows Presentation Foundation (WPF) client, you will need to make those calls asynchronously. While async calls have been around for a long time in Microsoft .NET, the patterns for addressing them have been changing and improving. This session covers several common patterns for addressing async calls in client applications, including new and emerging approaches to async patterns such as Reactive Extensions that let you treat asynchronous execution like a LINQ collection and the Task-based Async pattern and keywords coming for the C# and VB languages. This session takes the mystery and confusion out of what happens and when — and how to keep your code clean and safe in an inherently asynchronous client world.”

Video

Highlights

This session provided a practical overview of asynchrony from the perspective of the UI (and by extension the affinity that UI objects and ObservableCollection<T> has with the UI thread). Some rule-of-thumb tips are:

  • Never block the UI thread. If it takes longer than 50-60ms, async it.
  • Never access UI objects from a non-UI thread.
  • Don’t access variables from multiple threads with protection.

The asynchronous patterns provided by the .Net Framework are:

  • Begin/End Async Pattern
  • Async/Completed Pattern
  • Task Parallel Library (Task<T>)
  • Task-based Async (async and await keywords)
  • Reactive Extensions (LINQ + Observables + Schedulers)

Links