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

Demystifying .Net Asynchronous Programming

Info

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

“Asynchronous programming is no longer an option; it’s become a must on various platforms, including Silverlight, Windows Phone 7, and various data-centric frameworks. Unfortunately, dealing with asynchrony is way too hard in today’s world of development tools and frameworks. The huge amount of manual and error-prone plumbing leads to incomprehensible and hard to maintain code. As we reach out to services in the cloud, the desire for asynchronous computation is ever increasing, requiring a fresh look on the problems imposed by reactive programming. In this session, we explore various methodologies to address asynchronous programming, and explain how they relate and differ. First, we’ll explore existing patterns and libraries – such as the TPL – to sketch some of the pain-points. Armed with this knowledge, we’ll approach the problem from different angles, including a language-centric view with F#’s asynchronous workflows and the upcoming asynch and await features in C# and Visual Basic. Next, we’ll move beyond sequential composition of asynchronous computations, and introduce the Reactive Extensions (Rx) that enable you to express rich queries – even using LINQ syntax – over asynchronous push-based “reactive” event streams.”

Highlights

The discussion starts by introducing the concepts of Asynchrony (multiple parties evolving in time independently), Concurrency (order in which multiple tasks execute is not determined) and Parralelism (multiple tasks working together), and some wording (“Reactive”, “Callbacks”, “Events”) that typically describe asynchronous situations.

Abstractions in .Net that support asynchrony are: Asynchronous Programming Model (uses callback functions), Event-Based Asynchronous Pattern (uses completion events), and the BackgroundWorker Component.

New tools and abstractions being introduced in upcoming versions of C# and .Net include:

  • await keyword suspends the code that follows the keyword into a continuation for the asynchronous operation completion. The keyword (and the code following it) can be safely wrapped in standard control statements such as while{}, or try{} catch{} blocks.
  • Task<T> is a representation of computations (.StartNew()), and hooks (.ContinueWith()) for continuations (which allows for sequencing). Task.Result blocks the calling thread.
  • BeginVerb-EndVerb patterned functions and VerbAsync functions are complemented with VerbTaskAsync functions that return Task<T>.

Some code examples:

Example 1

1
2
3
var report = Task.Factory.StartNew(() => GetFileData())
			 .ContinueWith(x => Analyze(x.Result))
			 .ContinueWith(y => Summarize(y.Result));

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
async void DoWorkAsync() {
	var t1 = ProcessFeedAsync("x");
	var t2 = ProcessFeedAsync("y");
	await Task.WhenAll(t1, t2);
	DisplayMessage("Done");
}
 
async Task ProcessFeedAsync( string url ) {
	var text = await DownloadFeedAsync(url);
	var doc = ParseFeedIntoDoc(text);
	await SaveDocAsync(doc);
	ProcessLog.WriteEntry(url);
}

Reactive Extension (Rx)

Rx is a library for composing asynchronous and event-based programs using observable sequences. Think IObservable<T> and IObserver<T> (subscribe, push) vs. IEnumerable<T> and IEnumerator<T> (pull, blocking).

The concepts introduced by Rx are best studied through additional research into some of the functions it provides:

  • .Throttle()
  • .DistinctUntilChanged()
  • .TakeUntil()
  • .ObserveOn()
  • .Subscribe()

The relationship between the various paradigms is best visualized on a graph representing (Axis Y): Single Value vs. Multiple Values over (Axis X): Syncrhonous vs. Asynchronous … the four distinct quadrants of this graph are:

  • Single-Value Synchronous: Func<T>
  • Single-Value Asynchronous: Task<T> (and await)
  • Multiple-Value Synchronous: IEnumerable<T>
  • Multiple-Value Asynchronous: IObservable<T> (and .Subscribe())