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.

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

MVC, MVP & MVVM: Comparison of Architectural Patterns

Info

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

“This session compares the architectural patterns of Model-View-Controller (MVC), Model-View-Presenter (MVP) and Model-View-View Model (MVVM). Each pattern creates testable, maintainable and reusable application components, however, there are differences that suit each approach to specific types of developer tooling. The presentation first looks at the basic theory and differences between the approaches; then uses demos that show how each apply to Microsoft ASP.NET, Microsoft Silverlight/Windows Presentation Foundation (WPF) and Microsoft SharePoint developer application projects.”

Video

Highlights

The MVC pattern is distinct in that the user interacts directly with the Controller objects, while both others represent patters where the user interacts with the View objects. MVC is primarily suited for use in the ASP.Net MVC Framework, as the underlying concepts are fundamentaly built in to the framework itself. With some effort however, MVC can be implemented directly onto standard ASP.Net (which is of course what the MVC Framework essentially does for you). WinForms applications could also fit into the MVC paradigm, and can be built on this pattern with even less effort than standard ASP.Net. In this pattern: M = Model, V = View and C = Controller; where M is unaware of V and C, V is aware of M, and C is aware of both V and M.

MVP lends itself well to “standard” ASP.Net projects and SharePoint development, with the assumption (and indeed “requirement”) that while Views are the point of entry and interaction with the user, they “dumb [themselves] down” and relinquish control to the Presenters that they instantiate. In this pattern: M = Model, V = View and P = Presenter; where M is unaware of V and P, V is aware of P, and P is aware of both M and an interface representative of V.

MVVM is the most recent evolution of these “separation of concern” patterns, and is most useful in the XAML (Silverlight and WPF) environment, which has strong data- and command-binding support. Similar to MVP, Views in MVVM also defer all business logic to the ViewModel. Communication between View and ViewModel is facilitated through a combination of Command Bindings and Events (behaviour-driven communication) and Data Binding (data-driven communication). In this pattern: M = Model, V = View and VM = ViewModel; where M is unaware of V and VM, V is aware of VM, and VM is aware of M.