<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>jaredpar's WebLog : Threading</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx</link><description>Tags: Threading</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>A more usable API for a mutable thread safe collection</title><link>http://blogs.msdn.com/jaredpar/archive/2009/02/16/a-more-usable-thread-safe-collection.aspx</link><pubDate>Mon, 16 Feb 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9424930</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>17</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9424930.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9424930</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9424930</wfw:comment><description>
&lt;p&gt;In my last &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx" mce_href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx"&gt;post&lt;/a&gt; we discussed the problems with designing a safer API for mutable thread safe collections that employ only an internal locking system.&amp;nbsp; The result was an API that was more difficult to mess up, yet pretty much unusable.&amp;nbsp; Lets take a look at this problem and see if we can come up with a usable API that still helps to eliminate mistakes.&amp;nbsp; &lt;/p&gt;
  
&lt;p&gt;One of the main issues I have with mutable thread safe collections is the use of decision procedures such as Count and Contains.&amp;nbsp; Procedures such these only return information that pertains to the collection as it existed at a previous point in time.&amp;nbsp; It can provide no relevant information to the collection in it’s current state and only encourages the user to write bad code.&amp;nbsp; For example.&amp;nbsp; &lt;/p&gt;
  
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;    &lt;span style="color: green;"&gt;// Collection can be modified before this next line executes leading to &lt;br&gt;    // an error condition&lt;br&gt;    &lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[0]; &lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Therefore they have no place on a mutable thread safe collection.&amp;nbsp; Yet, once you take away these procedures, you’re left with a collection that is virtually useless.&amp;nbsp; It can only have a minimal API by which to access data.&amp;nbsp; Here is the last example we were left with &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) { ... }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryRemove(T value) { ... }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryGet(&lt;span style="color: blue;"&gt;int &lt;/span&gt;index, &lt;span style="color: blue;"&gt;out &lt;/span&gt;T value) { ... }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is hardly a usable API.&amp;nbsp; What’s worse, as wekempf point out, is that I inadvertently exposed a decision procedure in this API.&amp;nbsp; It’s possible to infer state about a lower or equal index by a successful return result from TryGet().&amp;nbsp; For example, a user may say that “if I can access element 2, then surely element 1 must exist”.&amp;nbsp; The result would still be evident in code (ignoring the return value of a TryGet method should be a red flag).&amp;nbsp; But a better choice for this method would have been a TryGetFirst().&amp;nbsp; &lt;/p&gt;

&lt;p&gt;At the end of the day, users are going to want some level of determinism out of their collections.&amp;nbsp; It’s possible to program against API’s like the above, but most people won’t do it.&amp;nbsp; In order to be more used, the collection must be able to reliably implement procedures such as Count and Contains and allow the user to use the return to reason about the state of the collection.&lt;/p&gt;

&lt;p&gt;One way to do this is to simply exposed the internal lock to the consumer of the collection.&amp;nbsp; Consumers can take the lock and then query to their hearts content.&amp;nbsp; Lets do a quick modification of the original sample to allow for this.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public object &lt;/span&gt;SyncLock { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_lock; } }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Remove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Contains(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Count; } } }&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;T &lt;span style="color: blue;"&gt;this&lt;/span&gt;[&lt;span style="color: blue;"&gt;int &lt;/span&gt;index] {&lt;br&gt;        &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list[index]; } }&lt;br&gt;        &lt;span style="color: blue;"&gt;set &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { m_list[index] = &lt;span style="color: blue;"&gt;value&lt;/span&gt;; } }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now we can go back to the original sample code and write a version which can use the decision procedures safely.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;lock &lt;/span&gt;(col.SyncLock) {&lt;br&gt;    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;        &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[0];&lt;br&gt;        ...&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code will function correctly.&amp;nbsp; But the API leaves a lot to be desired.&amp;nbsp; In particular … &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;It provides no guidance to the user as to which procedures must be accessed with the SyncLock object locked.&amp;nbsp; They can just as easily write the original bad sample code.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;
    
&lt;p&gt;All procedures used within the lock reacquire the lock recursively which is definitely &lt;a href="http://zaval.org/resources/library/butenhof1.html" mce_href="http://zaval.org/resources/library/butenhof1.html"&gt;not advisable&lt;/a&gt;.&amp;nbsp; We could provide properties which do not acquire the lock such as CountNoLock that work around this problem. While ok in small doses, it's just a matter of time before you see this snippet in the middle of a huge mostly undocumented function&lt;/p&gt;

    
&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// Lock should be held at this point&lt;br&gt;&lt;/span&gt;&lt;span style="color: blue;"&gt;int &lt;/span&gt;count = col.CountNoLock;&lt;/pre&gt;
    &lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
    
&lt;p&gt;This code makes my eyes bleed&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;The API provides 0 information to the user on exactly what the rules are for this lock.&amp;nbsp; It would be left as an artifact in documentation (which you simply cannot count on users reading).&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;There is really nothing telling the user that they ever have to unlock the collection.&amp;nbsp; Surely, any user entering into the world of threading should know this but if they do a Monitor.Enter call without a corresponding Monitor.Exit, they will receive no indication this is a bad idea.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;Overall this collection requires a lot of new knowledge about the collection to use &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This design though is exactly how a “synchronized” collection in 1.0 version of the BCL worked.&amp;nbsp; This code is essentially what you would get by passing an ArrayList instance to ArrayList.Synchronized (and most other BCL 1.0 collections).&amp;nbsp;&amp;nbsp; It was problematic enough that all of the new collections in 2.0 did not implement this &lt;i&gt;feature&lt;/i&gt;.&amp;nbsp; Here’s the BCL team’s explanation on this &lt;a href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" title="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" mce_href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx"&gt;http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Overall this design poses several problems because it exposes internal implementation details directly to the consumer.&amp;nbsp; An improved design should seek to hide the lock from direct access.&amp;nbsp; What we really want is a way to not even provide API’s like Count and Contains unless the object is already in a locked state.&amp;nbsp; This prevents them from being used at all in an incorrect scenario.&lt;/p&gt;

&lt;p&gt;Lets run with this idea to design a more usable thread safe queue.&amp;nbsp; First we’ll divide the interface for a queue into two parts.&amp;nbsp; &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;All procedures that have 0 reliance on the internal state of the collection.&amp;nbsp; Namely Enqueue, and Clear.&amp;nbsp; No state is required to use these methods &lt;/li&gt;

  
&lt;li&gt;All procedures that rely on the internal state of the collection to function correctly.&amp;nbsp; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The ThreadSafeQueue class will contain all of the methods in category #1.&amp;nbsp; It will also provide a method which returns an instance of an interface which has all of the methods in category #2.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43, 145, 175);"&gt;IDisposable&lt;/span&gt;{&lt;br&gt;    &lt;span style="color: blue;"&gt;int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }&lt;br&gt;    &lt;span style="color: blue;"&gt;bool &lt;/span&gt;Contains(T value);&lt;br&gt;    T Dequeue();&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The implementation of this interface object will acquire the internal lock of the original ThreadSafeQueue during construction and hold it for the duration if it’s lifetime.&amp;nbsp; This effectively freezes the queue allowing for decision procedures to be used reliably.&amp;nbsp; Implementing IDisposable and releasing the lock in the Dispose method provides a measure of lifetime management.&amp;nbsp;&amp;nbsp; &lt;/p&gt;

&lt;p&gt;The rest of the code sample is below.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;#region &lt;/span&gt;LockedQueue&lt;br&gt;    &lt;span style="color: blue;"&gt;private sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;        &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; m_outer;&lt;br&gt;        &lt;span style="color: blue;"&gt;internal &lt;/span&gt;LockedQueue(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; outer) {&lt;br&gt;            m_outer = outer;&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Enter(m_outer.m_lock);&lt;br&gt;        }&lt;br&gt;&lt;br&gt;        &lt;span style="color: blue;"&gt;#region &lt;/span&gt;ILockedQueue&amp;lt;T&amp;gt; Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;br&gt;            &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Count; }&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Contains(value);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;public &lt;/span&gt;T Dequeue() {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Dequeue();&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;        #region &lt;/span&gt;IDisposable Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Dispose() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;true&lt;/span&gt;);&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;GC&lt;/span&gt;.SuppressFinalize(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;private void &lt;/span&gt;Dispose(&lt;span style="color: blue;"&gt;bool &lt;/span&gt;disposing) {&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Debug&lt;/span&gt;.Assert(disposing, &lt;span style="color: rgb(163, 21, 21);"&gt;"ILockedQueue implementations must be explicitly disposed"&lt;/span&gt;); &lt;br&gt;            &lt;span style="color: blue;"&gt;if &lt;/span&gt;(disposing) {&lt;br&gt;                &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Exit(m_outer.m_lock);&lt;br&gt;            }&lt;br&gt;        }&lt;br&gt;        ~LockedQueue() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;false&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;    &lt;/span&gt;}&lt;br&gt;    &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;&lt;br&gt;    private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt; m_queue = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;ThreadSafeQueue() { }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Enqueue(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Enqueue(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Clear() {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Clear();&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; Lock() {&lt;br&gt;        &lt;span style="color: blue;"&gt;return new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue&lt;/span&gt;(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;

&lt;p&gt;This design now cleanly separates out the two modes by which the collection can be asked.&amp;nbsp; It completely hides the explicit synchronization aspects from the users and replaces it with design patterns (such as IDisposable) that they are likely already familiar with.&amp;nbsp; Now our original bad sample can be rewritten as follows.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static void &lt;/span&gt;Example1(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt; queue) {&lt;br&gt;    &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;locked = queue.Lock()) {&lt;br&gt;        &lt;span style="color: blue;"&gt;if &lt;/span&gt;(locked.Count &amp;gt; 0) {&lt;br&gt;            &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = locked.Dequeue();&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;No explicit synchronization code is needed by the user.&amp;nbsp; This design makes it much harder for the user to make incorrect assumptions or misuses of the collection.&amp;nbsp; The “decision procedures” are simply not available unless the collection is in a locked state.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;As with most thread safe designs, there are ways in which this code can be used incorrectly &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;
    
&lt;p&gt;Using an instance of ILockedQueue&amp;lt;T&amp;gt; after it’s been disposed.&amp;nbsp; This though is already considered taboo though and we can rely on existing user knowledge to help alleviate this problem.&amp;nbsp; Additionally, static analysis tools, such as FxCop, will flag this as an error.&lt;/p&gt;

    
&lt;p&gt;&amp;nbsp;&lt;/p&gt;

    
&lt;p&gt;With a bit more rigor this can also be prevented. Simply add a disposed flag and check it on entry into every method.&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;It’s possible for the user to maintain values, such as Count, between calls to Lock and use it to make an incorrect assumption about the state of the list.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;If the user fails to dispose the ILockedQueue&amp;lt;T&amp;gt; instance it will be forever locked.&amp;nbsp; Luckily FxCop will also flag this as an error since it’s an IDisposable.&amp;nbsp; It’s not a foolproof mechanism though. &lt;/li&gt;

  
&lt;li&gt;There is nothing that explicitly says to the user “please only use ILockedQueue&amp;lt;T&amp;gt; for a very short time”.&amp;nbsp; IDisposable conveys this message to a point but it’s certainly not perfect.&lt;/li&gt;

  
&lt;li&gt;The actual ILockedQueue&amp;lt;T&amp;gt; implementation is not thread safe.&amp;nbsp; Ideally users won’t pass instances of IDisposable between threads but it is something to think about.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The good news is that two of these flaws (1 and 3) are issues with existing types and tools are already designed to weed them out.&amp;nbsp; FxCop will catch common cases for both of them.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Also, many of these cases are considered bad code in the absence of a thread safe collection.&amp;nbsp; This allows users to rely on existing knowledge instead of forcing them to learn new design patterns for mutable thread safe collections.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Overall I feel like this design is a real win over the other versions.&amp;nbsp; It provides an API which helps to limit the mistakes a user can make with a mutable thread safe collection without requiring a huge deal of new patterns in order to use.&amp;nbsp; &lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9424930" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Why are thread safe collections so hard?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx</link><pubDate>Wed, 11 Feb 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9412190</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>52</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9412190.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9412190</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9412190</wfw:comment><description>&lt;p&gt;Writing a collection which is mutable, thread safe and usable is an extremely difficult process.&amp;nbsp; At least that’s what you’ve likely been told all through your schooling.&amp;nbsp; But then you get out on the web and see a multitude of thread safe lists, maps and queues.&amp;nbsp; If it’s so hard, why are there so many examples?&amp;nbsp; &lt;/p&gt;  &lt;p&gt;The problem is there are several levels of thread safe collections.&amp;nbsp; I find that when most people say thread safe collection what they really mean “a collection that will not be corrupted when modified and accessed from multiple threads”.&amp;nbsp;&amp;nbsp; Lets call this “data thread safe” for brevity.&amp;nbsp; This type of collection is rather easy to build.&amp;nbsp; Virtually any collection that is not thread safe can be made “data thread safe” by synchronizing access via a simple locking mechanism.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;For Example, lets build a data thread safe List&amp;lt;T&amp;gt;.&amp;nbsp; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Remove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Contains(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Count; } } }&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;T &lt;span style="color: blue;"&gt;this&lt;/span&gt;[&lt;span style="color: blue;"&gt;int &lt;/span&gt;index] {&lt;br&gt;        &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list[index]; } }&lt;br&gt;        &lt;span style="color: blue;"&gt;set &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { m_list[index] = &lt;span style="color: blue;"&gt;value&lt;/span&gt;; } }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: green;"&gt;// IEnumerable&amp;lt;T&amp;gt; left out&lt;br&gt;&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And there you have it.&amp;nbsp; The lock statement prevents concurrent access from multiple threads.&amp;nbsp; So the actual m_list instance is only ever accessed by a single thread at a time which is all it’s designed to do.&amp;nbsp; This means instances of ThreadSafeList&amp;lt;T&amp;gt; can be used from any thread without fear of corrupting the underlying data.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;But if building a data thread safe list is so easy, why doesn’t Microsoft add these standard collections in the framework?&lt;/p&gt;

&lt;p&gt;Answer: ThreadSafeList&amp;lt;T&amp;gt; is a virtually unusable class because the design leads you down the path to bad code.&lt;/p&gt;

&lt;p&gt;The flaws in this design are not apparent until you examine how lists are commonly used.&amp;nbsp; For example,&amp;nbsp; take the following code which attempts to grab the first element out of the list if there is one.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static int &lt;/span&gt;GetFirstOrDefault(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt; list) {&lt;br&gt;    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(list.Count &amp;gt; 0) {&lt;br&gt;        &lt;span style="color: blue;"&gt;return &lt;/span&gt;list[0];&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;return &lt;/span&gt;0;&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code is a classic race condition.&amp;nbsp; Consider the case where there is only one element in the list.&amp;nbsp; If another thread removes that element in between the if statement and the return statement, the return statement will throw an exception because it’s trying to access an invalid index in the list.&amp;nbsp; Even though ThreadSafeList&amp;lt;T&amp;gt; is data thread safe, there is nothing guaranteeing the validity of a return value of one call across the next call to the same object.&amp;nbsp;&amp;nbsp; &lt;/p&gt;

&lt;p&gt;I refer to procedures like Count as decision procedures.&amp;nbsp; They server only to allow you to make a decision about the underlying object.&amp;nbsp; Decision procedures on a concurrent object are virtually useless.&amp;nbsp; As soon as the decision is returned, you must assume the object has changed and hence you cannot use the result to take any action.&lt;/p&gt;

&lt;p&gt;Decision procedures are one of the reasons why &lt;a href="http://code.msdn.microsoft.com/BclExtras" mce_href="http://code.msdn.microsoft.com/BclExtras"&gt;Immutable Collections&lt;/a&gt; are so attractive.&amp;nbsp; They are both data thread safe and allow you to reason about there APIs.&amp;nbsp; Immutable Collections don’t change &lt;b&gt;ever.&amp;nbsp; &lt;/b&gt;Hence it’s perfectly ok to have decision procedures on them because the result won’t get invalidated.&lt;/p&gt;

&lt;p&gt;The fundamental issue with ThreadSafeList&amp;lt;T&amp;gt; is it is designed to act like a List&amp;lt;T&amp;gt;.&amp;nbsp; Yet List&amp;lt;T&amp;gt; is not designed for concurrent access.&amp;nbsp;&amp;nbsp; When building a mutable concurrent collection, in addition to considering the validity of the data, you must consider how design the API to deal with the constantly changing nature of the collection.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;When designing a concurrent collection you should follow different guidelines than for a normal collection class.&amp;nbsp; For example.&amp;nbsp; &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Don’t add an decision procedures.&amp;nbsp; They lead users down the path to bad code. &lt;/li&gt;

  &lt;li&gt;Methods which query the object can always fail and the API should reflect this. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Based on that, lets look at a refined design for ThreadSafeList&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryRemove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryGet(&lt;span style="color: blue;"&gt;int &lt;/span&gt;index, &lt;span style="color: blue;"&gt;out &lt;/span&gt;T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;( m_lock ) {&lt;br&gt;            &lt;span style="color: blue;"&gt;if&lt;/span&gt;( index &amp;lt; m_list.Count ) {&lt;br&gt;                value = m_list[index];&lt;br&gt;                &lt;span style="color: blue;"&gt;return true&lt;/span&gt;;&lt;br&gt;            }&lt;br&gt;            value = &lt;span style="color: blue;"&gt;default&lt;/span&gt;(T);&lt;br&gt;            &lt;span style="color: blue;"&gt;return false&lt;/span&gt;;&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Summary of the changes&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Both the Contains and Count procedures were removed because they were decision procedures &lt;/li&gt;

  &lt;li&gt;Remove was converted to TryRemove to indicate it’s potential to fail &lt;/li&gt;

  &lt;li&gt;The TryGet property was added and is reflective of the fragile nature of the method.&amp;nbsp; Sure it’s possible for users to simply ignore the return value and plow on with the invalid value.&amp;nbsp; However the API is not lulling the user into a false sense of security &lt;/li&gt;

  &lt;li&gt;The collection no longer implements IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; IEnumerable&amp;lt;T&amp;gt; is only valid when a collection is not changing under the hood.&amp;nbsp; There is no way to easily make this guarantee with a collection built this way and hence it was removed.&amp;nbsp; &lt;/li&gt;

  &lt;li&gt;The indexers were removed as well.&amp;nbsp; I’m a bit wishy washy in this particular point as there is nothing in the API which gives a user a false sense of security.&amp;nbsp; But at the same time mutable concurrent collections are dangerous and should be treated with a heightened sense of respect so the indexers were removed. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This version of ThreadSafeList is more resilient, but not immune to, accidental user failure.&amp;nbsp; The design tends to lead users on the path to better code.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;But is it really usable?&amp;nbsp; Would you use it in your application?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9412190" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Thread Local Storage template</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/21/thread-local-storage-template.aspx</link><pubDate>Mon, 21 Apr 2008 20:52:03 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8415085</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8415085.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8415085</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8415085</wfw:comment><description>&lt;p&gt;Thread local storage is another method of synchronization between threads.&amp;nbsp; It is different that most synchronization cases because instead of sharing state between threads it enables developers to have independent, thread specific pieces of data which have a similar or common purpose.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The uses of thread local storage (TLS) vary greatly but is a very powerful and lightweight method for storing data.&amp;nbsp; TLS can easily be envisioned as a giant void* array for every thread.&amp;nbsp; The entry point, TlsAlloc, provides an index into this array and allows the storage of arbitrary data [1].&lt;/p&gt; &lt;p&gt;TLS is particularly useful for storing state information.&amp;nbsp; For example, one of my components lives in a highly multi-threaded environment.&amp;nbsp; Each thread serves essentially the same purpose and has the same states and state transition semantics.&amp;nbsp; Like any good paranoid programmer I wanted to add contracts to check my state transitions and semantics.&amp;nbsp; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Contract.VerifyState(ExpectedState, ???CurrentState)&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The question is where to store the state information for a thread?&amp;nbsp; A global state variable won't suffice because there are N threads.&amp;nbsp; A global array of state information also has it's share of problems: synchronization, determining an index, lifetime. &lt;/p&gt; &lt;p&gt;TLS is ideally suited to this scenario.&amp;nbsp; Each thread has an independent but similar concept of state.&amp;nbsp; In my initialization code I allocate an TLS index and now I have a place to store my state.&amp;nbsp; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Contract.VerifyState(ExpectedState, *TlsGetValue(g_stateTlsIndex)&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The next question is how to manage the lifetime?&amp;nbsp; TLS provides a void* and the caller must manage the lifetime of the allocated memory.&amp;nbsp;&amp;nbsp; Since this is thread specific the ideal place is to manage the memory in the thread startup proc.&amp;nbsp; However I don't own the creation of the thread, my component is called on a number of threads so this won't work.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The solution is to use the stack.&amp;nbsp; The initial return for TlsGetValue is NULL.&amp;nbsp; If this situation is detected then the current stack frame is set to own the memory for the slot.&amp;nbsp; Further accesses to the value do not own the memory and simply access it.&amp;nbsp; The semantics are straight forward but annoying to constantly rewrite, so naturally write a template :)&lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
    &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; TlsValue
    {
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
        TlsValue(DWORD index, &lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; T&amp;amp; defaultValue=T()) :
            m_pValue(NULL),
            m_index(index),
            m_owns(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;)
        {
            m_pValue = &lt;span style="color: rgb(0,0,255)"&gt;reinterpret_cast&lt;/span&gt;&amp;lt;T*&amp;gt;(::TlsGetValue(m_index));
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; ( !m_pValue )
            {
                m_pValue = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; T(defaultValue);
                m_owns = &lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;;
                ::TlsSetValue(m_index, m_pValue);
            }
        }
        ~TlsValue()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; ( m_owns )
            {
                ::TlsSetValue(m_index, NULL);
                &lt;span style="color: rgb(0,0,255)"&gt;delete&lt;/span&gt; m_pValue;
            }
        }

        T* Value() &lt;span style="color: rgb(0,0,255)"&gt;const
&lt;/span&gt;        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_pValue;
        }

    &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
        &lt;span style="color: rgb(0,128,0)"&gt;// Do not auto generate
&lt;/span&gt;        TlsValue();
        TlsValue(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; TlsValue&amp;lt;T&amp;gt;&amp;amp;);
        TlsValue&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; TlsValue&amp;lt;T&amp;gt;&amp;amp;);

        T* m_pValue;
        DWORD m_index;
        &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; m_owns;
    };
&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In addition to this blog post, I added a working sample to &lt;a title="http://code.msdn.microsoft.com/TlsValue" href="http://code.msdn.microsoft.com/TlsValue"&gt;http://code.msdn.microsoft.com/TlsValue&lt;/a&gt;.&amp;nbsp; This is my first attempt at posting a sample on &lt;a href="http://code.msdn.com"&gt;http://code.msdn.com&lt;/a&gt; so please provide any and all feedback on the data.&lt;/p&gt;
&lt;p&gt;[1] This is similar to data marked with the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx"&gt;ThreadStatic attribute&lt;/a&gt; in managed code without all of the slot messiness and with the added benefit of strong typing.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8415085" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category></item><item><title>ActiveObject</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/30/activeobject.aspx</link><pubDate>Sun, 30 Mar 2008 19:39:28 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8344411</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8344411.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8344411</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8344411</wfw:comment><description>&lt;p&gt;I've been busy lately and neglected my series on &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/28/active-objects-and-futures.aspx"&gt;Active Objects&lt;/a&gt;.&amp;#160; It's been a fairly busy time for me both in and out of work.&amp;#160; Enough excuses, back to the fun.&lt;/p&gt;  &lt;p&gt;With the basic &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx"&gt;PipeSingleReader&lt;/a&gt; class, we now have the last piece necessary to create an ActiveObject.&amp;#160; This article will focus on building the base ActiveObject which will take care of scheduling, construction, destruction and error handling.&amp;#160; The goal is to make implementing an ActiveObject that actually does work easy.&amp;#160; &lt;/p&gt;  &lt;p&gt;Lets break down the implementation of an ActiveObject into the three phases of any object; construction, destruction and running behavior. &lt;/p&gt;  &lt;h3&gt;Construction&lt;/h3&gt;  &lt;p&gt;Active Objects are associated with and have an affinity to a particular thread.&amp;#160; Constructing an ActiveObject mainly consists of creating a thread and initializing the member variables of the object.&amp;#160; &lt;/p&gt;  &lt;p&gt;There are a couple of requirements that need to be met when initializing the object.&amp;#160; The first is getting the thread into a known state before returning out of the constructor.&amp;#160; It's possible for coders to create and then immediately destroy an object.&amp;#160; Part of destructing an object is understanding the state you are destructing.&amp;#160; Returning from an ActiveObject constructor before the thread is up and running means that we can be destructed while in an inconsistent state.&amp;#160; Normally this isn't much an issue with objects because they are single threaded.&amp;#160; We will fix this by doing a simple wait until the thread is finished initializing.&lt;/p&gt;  &lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; ActiveObject() {
            m_thread = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;(() =&amp;gt; InitializeAndRunBackgroundThread());
            m_thread.Start();
            &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (0 == m_backgroundInitialized) { &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.Sleep(0); }
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Next is providing implementers with a way to initialize member variables on the new thread.&amp;#160; There are many reasons for wanting to initialize members on the ActiveObject thread.&amp;#160; Besides general consistency concerns, there is also the issue that objects can have affinity to a particular thread and including forcing initialization to occur on that thread.&amp;#160; To make this simple part of the thread initialization code will call a virtual method allowing base classes to initialize variables.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; InitializeAndRunBackgroundThread() {
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_affinity, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ThreadAffinity&lt;/span&gt;());
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_pipe, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;PipeSingleReader&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;gt;());
            InitializeMembersInBackground();
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_backgroundInitialized, 1);
            RunBackgroundActions();
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;virtual&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; InitializeMembersInBackground() {
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h3&gt;Running Behavior&lt;/h3&gt;

&lt;p&gt;Active Objects exist for one reason, to run Futures.&amp;#160; The main behavior is to loop over the set of Futures and run them.&amp;#160; The PipeSingleReader class takes care of most of the scheduling and threading work.&amp;#160; This leaves the ActiveObject free to make policy decisions.&amp;#160; &lt;/p&gt;

&lt;p&gt;One question that comes up is how to handle the case where a Future throws an exception?&amp;#160; If we run the Future with no protection it will simple cause an unhandled exception and likely a process crash.&amp;#160; We could catch and try to filter them but based on what criteria?&amp;#160; IMHO there is no way to properly handle an exception in the Active Object base because we don't know what the purpose of that object is.&amp;#160; Only the actual object implementer knows.&amp;#160; Therefore we will make it their problem by passing unhandled exceptions into an abstract method.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunBackgroundActions() {
            &lt;span style="color: rgb(0,0,255)"&gt;do&lt;/span&gt; {
                RunFuture(m_pipe.GetNextOutput());
            } &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (0 == m_backgroundFinished);
            &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; future;
            &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (m_pipe.TryGetOutput(&lt;span style="color: rgb(0,0,255)"&gt;out&lt;/span&gt; future)) {
                RunFuture(future);
            }
        }
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunFuture(&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; future) {
            &lt;span style="color: rgb(0,0,255)"&gt;try&lt;/span&gt; {
                m_affinity.Check();
                future.Run();
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; ex) {
                OnBackgroundUnhandledException(ex);
            }
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;If the second loop looks a bit out of place, hopefully the destruction section will explain it's purpose.&lt;/p&gt;

&lt;p&gt;All that is left is to provide helper methods to let base classes queue up Futures to run.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; RunInBackground(&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt; action) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(action);
            m_pipe.AddInput(f);
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt; RunInBackground&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; func) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(func);
            m_pipe.AddInput(f);
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h3&gt;Destruction&lt;/h3&gt;

&lt;p&gt;Destruction of an ActiveObject can be tricky with respect to handling pending actions.&amp;#160; Should they be executed, aborted or just completely ignored?&amp;#160; What happens if more input is added once we start the dispose process?&amp;#160; If we don't allow more input where should we error?&amp;#160; &lt;/p&gt;

&lt;p&gt;IMHO, the simplest user and programming model is the following.&amp;#160; &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Dispose is synchronous.&amp;#160; It will block until the background thread is destroyed.&amp;#160; Dispose is the equivalent of destruction so it follows that all resources including the thread will be destroyed when destruction completes.&lt;/li&gt;

  &lt;li&gt;Once dispose starts input will be stopped.&amp;#160; This prevents live-lock scenarios where one thread is disposing the ActiveObject and another thread is constantly adding data.&amp;#160; &lt;/li&gt;

  &lt;li&gt;If another thread tries to add an operation during the middle of disposing they will be given an exception at that time.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In future posts, we'll explore how to create ActiveObjects with differing dispose semantics.&amp;#160; &lt;/p&gt;

&lt;p&gt;Now how can we signal the background thread that we are done processing?&amp;#160; Just add a future to the queue to be running.&amp;#160; Because this will run on the only thread reading the int there is no need for an Interlocked operation.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Dispose(&lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; disposing) {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (disposing) {
                m_pipe.AddInput(&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(() =&amp;gt; { m_backgroundFinished = 1; }));
                m_pipe.CloseInput();
                m_thread.Join();
            }
        }&lt;/pre&gt;

&lt;p&gt;Now that we've gone over the dispose code, hopefully the reason for the second loop in RunBackgroundActions is a little more apparent.&amp;#160; Between the two calls to m_pipe in Dispose another thread can post a Future.&amp;#160; Without the second loop the user will get no exception and the future will never run.&amp;#160; Likely they would hopelessly deadlock.&amp;#160;&amp;#160; The second loop will run all Futures which get caught it this gap.&amp;#160; &lt;/p&gt;

&lt;h3&gt;The Code&lt;/h3&gt;

&lt;p&gt;Here is the full version of the code. &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;abstract&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ActiveObject&lt;/span&gt; :  &lt;span style="color: rgb(43,145,175)"&gt;IDisposable&lt;/span&gt; {
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;PipeSingleReader&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;gt; m_pipe;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ThreadAffinity&lt;/span&gt; m_affinity;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt; m_thread;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_backgroundInitialized;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_backgroundFinished;

        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; ActiveObject() {
            m_thread = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;(() =&amp;gt; InitializeAndRunBackgroundThread());
            m_thread.Start();
            &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (0 == m_backgroundInitialized) { &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.Sleep(0); }
        }
&lt;span style="color: rgb(0,0,255)"&gt;        #region&lt;/span&gt; Dispose
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Dispose() {
            Dispose(&lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;);
            &lt;span style="color: rgb(43,145,175)"&gt;GC&lt;/span&gt;.SuppressFinalize(&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;);
        }
        ~ActiveObject() {
            Dispose(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;);
        }
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Dispose(&lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; disposing) {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (disposing) {
                m_pipe.AddInput(&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(() =&amp;gt; { m_backgroundFinished = 1; }));
                m_pipe.CloseInput();
                m_thread.Join();
            }
        }
&lt;span style="color: rgb(0,0,255)"&gt;        #endregion
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; InitializeAndRunBackgroundThread() {
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_affinity, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ThreadAffinity&lt;/span&gt;());
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_pipe, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;PipeSingleReader&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;gt;());
            InitializeMembersInBackground();
            &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_backgroundInitialized, 1);
            RunBackgroundActions();
        }
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunBackgroundActions() {
            &lt;span style="color: rgb(0,0,255)"&gt;do&lt;/span&gt; {
                RunFuture(m_pipe.GetNextOutput());
            } &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (0 == m_backgroundFinished);
            &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; future;
            &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (m_pipe.TryGetOutput(&lt;span style="color: rgb(0,0,255)"&gt;out&lt;/span&gt; future)) {
                RunFuture(future);
            }
        }
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunFuture(&lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; future) {
            &lt;span style="color: rgb(0,0,255)"&gt;try&lt;/span&gt; {
                m_affinity.Check();
                future.Run();
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; ex) {
                OnBackgroundUnhandledException(ex);
            }
        }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; RunInBackground(&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt; action) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(action);
            m_pipe.AddInput(f);
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt; RunInBackground&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; func) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.CreateNoRun(func);
            m_pipe.AddInput(f);
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;virtual&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; InitializeMembersInBackground() {
        }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;abstract&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; OnBackgroundUnhandledException(&lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; ex);
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8344411" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Active+Object/default.aspx">Active Object</category></item><item><title>PipeSingleReaderNoLock</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/03/pipesinglereadernolock.aspx</link><pubDate>Mon, 03 Mar 2008 08:46:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7996040</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7996040.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7996040</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7996040</wfw:comment><description>&lt;P&gt;Previously we discussed a multi-thread safe &lt;A href="http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx" mce_href="http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx"&gt;queue like data structure&lt;/A&gt; using locks as an internal synchronization mechanism.&amp;nbsp; This time we'll look at a version requiring no locks.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In the previous version, locks were used to synchronize access to an underlying queue which stored the data.&amp;nbsp; Removing the locks necessitates us moving away from Queue&amp;lt;T&amp;gt; to store the data and forces us onto another structure which is safe in the presence of multiple threads.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Immutable collections are safe in the presence of multiple threads and don't require any synchronization mechanisms.&amp;nbsp; However they're immutable and we're trying to build a mutable data structure?&amp;nbsp; No matter.&amp;nbsp; Even though each instance is immutable they can be used to create new instances which represent a somewhat mutated state.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;For this exercise we will be using a slight variant of Eric Lippert's &lt;A href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx"&gt;Immutable Stack&lt;/A&gt; implementation [1].&amp;nbsp; The pipe will have two stacks; 1) for capturing input and 2) for storing output.&amp;nbsp; Named m_writeStack and m_readStack respectively.&lt;/P&gt;
&lt;P&gt;This makes the implementation of reading input straight forward.&amp;nbsp; While m_readStack is not empty the reader thread can systematically pop off the values.&amp;nbsp; This doesn't require any contention with writer threads and since their is only one reader thread and the stack is immutable the code is straight forward.&amp;nbsp; Once the m_readStack is empty the reader thread will swap out the current state of m_writeStack with an empty stack.&amp;nbsp; The original value will be reversed so we can maintain the FIFO ordering and set as the new m_readStack.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; CheckForInput() {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt;( m_readerStack.IsEmpty ) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; prev = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.Exchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty);
        m_readerStack = prev.Reverse();
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; !m_readerStack.IsEmpty;
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Writing data is more complicated because it must deal with contention for updating the same data structure.&amp;nbsp; It can be altered by other writers or the reader thread when it runs out of data.&amp;nbsp; Basically it must push a value onto the stack and update the m_writerStack to point to the new value.&amp;nbsp; In between the operations the value of m_writerStack could change and thus invalidate the push.&amp;nbsp; To guard against this the writer must guarantee the current value of the m_writerStack is the same as it was before the push operation.&amp;nbsp; Interlocked.CompareExchange will do the trick.&amp;nbsp; If it's been changed then repeat the operation.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AddInput(T value) {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; done;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;do&lt;/SPAN&gt; {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_inputClosed) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;InvalidOperationException&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(163,21,21)"&gt;"Input end of pipe is closed"&lt;/SPAN&gt;);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; originalStack = m_writerStack;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; newStack = originalStack.Push(value);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; currentStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.CompareExchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, newStack, originalStack);
        done = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt;.ReferenceEquals(currentStack, originalStack);
    } &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!done);
    m_event.Set();
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;At a glance it may seem like this suffers from the &lt;A href="http://en.wikipedia.org/wiki/ABA_problem" mce_href="http://en.wikipedia.org/wiki/ABA_problem"&gt;ABA problem&lt;/A&gt;.&amp;nbsp; This is not the case and it's easy to prove.&amp;nbsp; In between the read and push operation only two other operations can modify the m_writeStack variable.&amp;nbsp; The first is another write which will produce a new value of ImmutableStack&amp;lt;T&amp;gt;.&amp;nbsp; In this case the CLR guarantees that the references will not be equal and the CAS operation won't succeed.&amp;nbsp; The second is the reader thread swaps out the value and replaces it with Empty.&amp;nbsp; It's possible to hit an ABA situation here (detailed below) but fundamentally if it was empty before and empty now the operation is still safe.&amp;nbsp; No data is lost&amp;nbsp;because we are still replacing an empty stack with a single value'd stack.&amp;nbsp;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here's a more elaborate version starting with an empty pipe of type int&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Thread 1: Begins to write 5 and is stopped just before the CAS operation&lt;/LI&gt;
&lt;OL&gt;
&lt;LI&gt;originalStack points to ImmutableStack&amp;lt;int&amp;gt;.Empty&lt;/LI&gt;&lt;/OL&gt;
&lt;LI&gt;Thread 2: Starts and completes a write of the value 6&lt;/LI&gt;
&lt;LI&gt;Thread 3: Reads a value from the pipe, having no data replaces m_writeStack with ImmutableStack&amp;lt;int&amp;gt;.Empty&lt;/LI&gt;
&lt;LI&gt;Thread 1: Resumes and the CAS succeeds even though the m_writeStack technically changed in the middle of the operation&lt;/LI&gt;&lt;/OL&gt;
&lt;P&gt;Even though this exhibits many characterstics of the ABA pattern it is not a problem because the behavior is still correct.&amp;nbsp; No data was lost because it was transferred to the reader thread.&amp;nbsp;&amp;nbsp;The end result is m_writeStack pointing to a single vaue'd stack containing the data 5 which is valid.&amp;nbsp;&amp;nbsp;The pipe does not guarantee the ordering of data between writer threads (merely the ordering between a single writer thread).&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Below is the implementation in it's entirety.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;PipeSingleReaderNoLock&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IDisposable&lt;/SPAN&gt; {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt; m_affinity = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt;();
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt; m_readerStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt; m_writerStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt; m_event = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;volatile&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; m_inputClosed;

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; PipeSingleReaderNoLock() {
    }

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;    #region&lt;/SPAN&gt; Dispose
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose() {
        Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;);
        &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;GC&lt;/SPAN&gt;.SuppressFinalize(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;);
    }
    ~PipeSingleReaderNoLock() {
        Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; disposing) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (disposing) {
            m_event.Close();
        }
    }
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;    #endregion
&lt;/SPAN&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; WaitForOutput() {
        m_affinity.Check();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!CheckForInput()) {
            m_event.WaitOne();
        }
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; T GetNextOutput() {
        m_affinity.Check();
        T data;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; data)) {
            m_event.WaitOne();
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; data;
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; T value) {
        m_affinity.Check();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (CheckForInput()) {
            value = m_readerStack.Peek();
            m_readerStack = m_readerStack.Pop();
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;else&lt;/SPAN&gt; {
            value = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;default&lt;/SPAN&gt;(T);
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;;
        }
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; CheckForInput() {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_readerStack.IsEmpty) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; prev = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.Exchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty);
            m_readerStack = prev.Reverse();
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; !m_readerStack.IsEmpty;
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AddInput(T value) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; done;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;do&lt;/SPAN&gt; {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_inputClosed) {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;InvalidOperationException&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(163,21,21)"&gt;"Input end of pipe is closed"&lt;/SPAN&gt;);
            }
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; originalStack = m_writerStack;
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; newStack = originalStack.Push(value);
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; currentStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.CompareExchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, newStack, originalStack);
            done = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt;.ReferenceEquals(currentStack, originalStack);
        } &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!done);
        m_event.Set();
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CloseInput() {
        m_inputClosed = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
    }&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;[1] If you haven't read this series you really should.&amp;nbsp; &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7996040" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category></item><item><title>PipeSingleReader</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx</link><pubDate>Sun, 02 Mar 2008 20:53:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7991808</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7991808.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7991808</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7991808</wfw:comment><description>&lt;P&gt;Before we can get to building an Active Object implementation, there are some more primitive structures we need to define.&amp;nbsp; Active Objects live on a separate thread where every call is executed in a serialized fashion on that thread.&amp;nbsp; The next primitive will allow us to easily pass messages in the form of delegates from the caller to the background thread.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The structure must support adding messages from N callers but only needs to support 1 reader (the active object).&amp;nbsp; Successive writes from the same thread should add the items in their respective order.&amp;nbsp; The input end of the pipe can be closed while leaving the output end active.&amp;nbsp; This allows for the consumer to deterministically reach an end state while not ignoring any any input.&lt;/P&gt;
&lt;P&gt;The name of the structure is PipeSingleReader.&lt;/P&gt;
&lt;P&gt;Designing a thread safe mutable structure is significantly different from a non-thread safe or immutable data structure.&amp;nbsp; There is a significant temptation to apply existing patterns.&amp;nbsp; We should question every pattern we apply to these collections.&amp;nbsp; Many of these patterns lead us to design API's which encourage bad programming practices. &lt;/P&gt;
&lt;P&gt;Our existing collection patterns are designed around structures which behave deterministically on any given thread because they are 1) Immutable or 2) designed for single thread use only.&amp;nbsp; Many of these concepts do not apply to mutable thread safe collections because they are constantly being accessed and mutated by multiple threads.&amp;nbsp; This gives them the &lt;EM&gt;appearance &lt;/EM&gt;of behaving non-deterministically with respect to a given thread.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Take the member Count for instance.&amp;nbsp; This is found on virtually every collection class in the BCL.&amp;nbsp; Yet having it on a mutable thread safe collection class only leads to programming errors.&amp;nbsp; The only reason to have a member such is Count is to use it to make a decision.&amp;nbsp;&amp;nbsp; However in a mutable thread-safe collection making a decision off of this value is wrong.&amp;nbsp; The value can and will change between any two instructions in code.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Take the example below.&amp;nbsp; Just because the Count is &amp;gt;0 in the if block has no dependable relevance to what the value will be inside the if block.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; ThreadSafeList&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt; col = GetList();
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt;( col.Count &amp;gt; 0 )
            {
                &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;//...
&lt;/SPAN&gt;            }&lt;/PRE&gt;
&lt;P&gt;To guard against this and have users of the collections avoid the pit of failure members such as Count should not appear on mutable thread-safe collections.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Instead we'll design API's around the functionality of this structure.&amp;nbsp; The input end of the structure is straight forward.&amp;nbsp; All writers want is to add data.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The output end is more interesting.&amp;nbsp; The end goal is to read output from the pipe but how to deal with cases where there is no data.&amp;nbsp;&amp;nbsp; Some programs will want to check for data, others block until data is available.&amp;nbsp;&amp;nbsp; We can define three methods to satisfy most scenarios&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;WaitForOutput - void method which blocks until input is available&lt;/LI&gt;
&lt;LI&gt;GetNextOutput - Blocks until input is available and returns it&lt;/LI&gt;
&lt;LI&gt;TryGetOutput - Returns immediately.&amp;nbsp; If output is available it will be returned.&lt;/LI&gt;&lt;/UL&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;PipeSingleReader&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IDisposable&lt;/SPAN&gt; {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt; m_affinity = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt;();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Queue&lt;/SPAN&gt;&amp;lt;T&amp;gt; m_queue = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Queue&lt;/SPAN&gt;&amp;lt;T&amp;gt;();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt; m_event = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt; m_lock = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt;();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; m_inputClosed;

        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; PipeSingleReader() {
        }

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;        #region&lt;/SPAN&gt; Dispose
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose() {
            Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;GC&lt;/SPAN&gt;.SuppressFinalize(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;);
        }
        ~PipeSingleReader() {
            Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; disposing) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (disposing) {
                m_event.Close();
            }
        }
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;        #endregion
&lt;/SPAN&gt;        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; WaitForOutput() {
            m_affinity.Check();
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;do&lt;/SPAN&gt; {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;lock&lt;/SPAN&gt; (m_lock) {
                    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_queue.Count &amp;gt; 0) {
                        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt;;
                    }
                }
                m_event.WaitOne();
            } &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; T GetNextOutput() {
            m_affinity.Check();
            T data;
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; data))
            {
                m_event.WaitOne();
            } 
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; data;
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; T value) {
            m_affinity.Check();
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;lock&lt;/SPAN&gt; (m_lock) {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_queue.Count == 0) {
                    value = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;default&lt;/SPAN&gt;(T);
                    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;;
                }

                value = m_queue.Dequeue();
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
            }
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AddInput(T value) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;lock&lt;/SPAN&gt; (m_lock) {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_inputClosed) {
                    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;InvalidOperationException&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(163,21,21)"&gt;"Input end of pipe is closed"&lt;/SPAN&gt;);
                }
                m_queue.Enqueue(value);
            }
            m_event.Set();
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CloseInput() {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;lock&lt;/SPAN&gt; (m_lock) {
                m_inputClosed = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
            }
        }
    }&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;At a quick glance it may seem odd in GetNextOutput that I loop around m_event being set and TryGetOutput.&amp;nbsp; Why loop?&amp;nbsp; Shouldn't a single check for the settness of m_event be enough?&amp;nbsp; In this case no.&amp;nbsp; The reason why is TryGetOutput will remove output from the queue without resetting the settness of m_event.&amp;nbsp; Thus m_event can be set without actually having any data in m_queue.&amp;nbsp; In general the implementation must treat m_event being set as the possibility of data rather than a guarantee.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;This implementation uses locks to synchronize access to the data.&amp;nbsp; In general I'm a fan of avoiding locks when possible since it's very easy to miss trivial cases.&amp;nbsp; Next time we'll look at an implementation of PipeSingleReader which avoids the use of locks.&amp;nbsp; &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7991808" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Active+Object/default.aspx">Active Object</category></item><item><title>SynchronizationContext and Higher Order Functions</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/24/synchronizationcontext-and-higher-order-functions.aspx</link><pubDate>Sun, 24 Feb 2008 12:42:48 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7874717</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7874717.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7874717</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7874717</wfw:comment><description>&lt;p&gt;It's often useful to ensure that actions occur on specific threads, in particular event handlers.&amp;#160; Take Windows Forms for instance where all operations on a Control must occur on the thread it was created on.&amp;#160; Typically this is not a problem since WinForms respond to events such as Click, Move, etc...&amp;#160; These events are sourced from the same thread so it's not an issue.&amp;#160; &lt;/p&gt;  &lt;p&gt;But there are cases where events are sourced from a separate thread and we need to Marshal it back onto the Control thread.&amp;#160; One good example of this is &lt;a href="http://msdn2.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx"&gt;FileSystemWatcher&lt;/a&gt;.&amp;#160; If a SynchronizationObject is not provided it will raise the event on an unspecified thread.&amp;#160; This event cannot directly touch a Control or an &amp;quot;Illegal cross thread call exception&amp;quot; will occur.&amp;#160; Many examples use ISynchronizedInvoke to marshal the code back.&amp;#160; There are a couple of downsides to this approach including&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;ISynchronizedInvoke on Controls won't work until the Handle is created or after it's destroyed.&amp;#160; So if the event fires in either of these cases an unhandled exception will occur and typically crash the process. &lt;/li&gt;    &lt;li&gt;Can't use an anonymous lambda because ISynchronizedInvoke is not typed to a specific delegate &lt;/li&gt;    &lt;li&gt;Code is easy to get subtly wrong &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Here is an example implementation.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; OnFileChanged(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; sender, &lt;span style="color: rgb(43,145,175)"&gt;FileSystemEventArgs&lt;/span&gt; e)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt;( &lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;.InvokeRequired )
            {
                &lt;span style="color: rgb(0,128,0)"&gt;// If the handle is not created this will throw
&lt;/span&gt;                Invoke((&lt;span style="color: rgb(43,145,175)"&gt;MethodInvoker&lt;/span&gt;)(() =&amp;gt; OnFileChanged(sender, e)));
                &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt;;
            }

            textBox2.Text = &lt;span style="color: rgb(43,145,175)"&gt;String&lt;/span&gt;.Format(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;{0} {1}&amp;quot;&lt;/span&gt;, e.ChangeType, e.Name);
        }&lt;/pre&gt;

&lt;p&gt;It would be easier if we could bind a delegate to a particular thread in such way that calls automatically marshal to the appropriate thread.&amp;#160; Imagine for instance if we could type the following in such a way that all invocations of &amp;quot;del&amp;quot; below would automatically marshal to the thread for the Control.&amp;#160; We could then freely pass this to any event source and not have to worry about what thread the event is raised on.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; del = &lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt;.Current.BindDelegateAsPost(&lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FileSystemEventHandler&lt;/span&gt;(OnFileChanged));&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Instead of ISynchronizedInvoke we'll use &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt;.&amp;#160; IMHO this is a better approach for this type of work.&amp;#160; It has the same functionality as ISynchronizedInvoke and helps with a few of the quirks.&amp;#160; The Windows Forms Application Model (and if memory serves WPF) insert a &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; for every thread running a WinForm application.&amp;#160; It greatly reduces the chance your code will run into problem #1 above because the timespan for when it can be used to Marshal between threads is not dependent upon the internal workings of a particular Control.&amp;#160; Instead it's tied to the lifetime of the Thread[1].&amp;#160; &lt;/p&gt;

&lt;p&gt;The basic strategy we'll take is to create a new delegate which wraps the original delegate.&amp;#160; This will Marshal the call onto the appropriate thread and then call the original delegate. &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; has two methods to Marshal calls between threads; Post and Send.&amp;#160; &lt;/p&gt;

&lt;p&gt;Creating a delegate instance on the fly is not straight forward.&amp;#160; Unless we code all permutations of delegate signatures into a class we cannot use the Delegate.Create API because we cannot provide a method with the matching signature.&amp;#160; Instead we need to go through Reflection.Emit.&amp;#160; This allows us to build a method on the fly to match the delegate signature.&amp;#160; In addition we can generate the IL to route the code through Post/Send before calling the delegate.&lt;/p&gt;

&lt;p&gt;First up are extension methods for &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; that call into a helper class.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; T BindDelegateAsPost&amp;lt;T&amp;gt;(&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, T del)
{
    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;DelegateFactory&lt;/span&gt;.CreateAsPost(context, del);
} &lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; T BindDelegateAsSend&amp;lt;T&amp;gt;(&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, T del)
{
    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;DelegateFactory&lt;/span&gt;.CreateAsSend(context, del);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Next is a class which injects the Send/Post call.&amp;#160; We need this as a storage mechanism for holding the context and delegate.&amp;#160; Essentially this is a hand generate closure.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;DelegateData
&lt;/span&gt;    {
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; m_context;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Delegate&lt;/span&gt; m_target;

        &lt;span style="color: rgb(0,0,255)"&gt;internal&lt;/span&gt; DelegateData(&lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, &lt;span style="color: rgb(43,145,175)"&gt;Delegate&lt;/span&gt; target)
        {
            m_target = target;
            m_context = context;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Send(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;[] args)
        {
            m_context.Send(() =&amp;gt; m_target.DynamicInvoke(args));
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Post(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;[] args)
        {
            m_context.Post(() =&amp;gt; m_target.DynamicInvoke(args));
        }
    }&lt;/pre&gt;

&lt;p&gt;Now comes the actual delegate generation.&amp;#160; The dynamic method will be bound to an instance of the DelegateData class.&amp;#160; As such we must add an additional parameter to the delegate of type DelegateData in position 0.&amp;#160; The rest of the method creates an object array with length equal to the number of parameters in the delegate.&amp;#160; Each of the arguments are added to this array.&amp;#160; Then it will call Post/Send in DelegateData passing the arguments along.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; T Create&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, T target, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; name)
    {
        &lt;span style="color: rgb(43,145,175)"&gt;Delegate&lt;/span&gt; del = (&lt;span style="color: rgb(43,145,175)"&gt;Delegate&lt;/span&gt;)(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;)target;
        &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (del.Method.ReturnType != &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt;))
        {
            &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;Only void return types currently supported&amp;quot;&lt;/span&gt;);
        }

        &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; paramList = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Type&lt;/span&gt;&amp;gt;();
        paramList.Add(&lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;DelegateData&lt;/span&gt;));
        paramList.AddRange(del.Method.GetParameters().Project((x) =&amp;gt; x.ParameterType));
        &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; method = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;DynamicMethod&lt;/span&gt;(
            &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;AMethodName&amp;quot;&lt;/span&gt;,
            del.Method.ReturnType,
            paramList.ToArray(),
            &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;DelegateData&lt;/span&gt;));
        &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; gen = method.GetILGenerator();
        &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; localInfo = gen.DeclareLocal(&lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;[]));
        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldc_I4, paramList.Count - 1);
        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Newarr, &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;));
        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Stloc, localInfo.LocalIndex);
        &lt;span style="color: rgb(0,0,255)"&gt;for&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; i = 1; i &amp;lt; paramList.Count; ++i)
        {
            gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldloc, localInfo.LocalIndex);
            gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldc_I4, i - 1);
            gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldarg, i);
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (paramList[i].IsValueType)
            {
                gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Box);
            }
            gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Stelem_Ref);
        }

        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldarg_0);
        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ldloc, localInfo.LocalIndex);
        gen.EmitCall(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Call, &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;DelegateData&lt;/span&gt;).GetMethod(name, &lt;span style="color: rgb(43,145,175)"&gt;BindingFlags&lt;/span&gt;.Instance | &lt;span style="color: rgb(43,145,175)"&gt;BindingFlags&lt;/span&gt;.Public), &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;);
        gen.Emit(&lt;span style="color: rgb(43,145,175)"&gt;OpCodes&lt;/span&gt;.Ret);
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; (T)(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;)method.CreateDelegate(&lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(T), &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;DelegateData&lt;/span&gt;(context, del));
    }

    &lt;span style="color: rgb(0,0,255)"&gt;internal&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; T CreateAsSend&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, T target)
    {
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Create(context, target, &amp;quot;Send&amp;quot;);
    }

    &lt;span style="color: rgb(0,0,255)"&gt;internal&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; T CreateAsPost&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;SynchronizationContext&lt;/span&gt; context, T target)
    {
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Create(context, target, &amp;quot;Post&amp;quot;);
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The resulting delegate is now of the same type as the original delegate and invocations will occur on the targeted thread.&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] Granted if you try to use a &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; to Marshal between threads after the target thread has finished you will still get an error.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7874717" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/SynchronizationContext/default.aspx">SynchronizationContext</category></item><item><title>Thread Affinity</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/22/thread-affinity.aspx</link><pubDate>Sat, 23 Feb 2008 04:55:20 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7852845</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7852845.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7852845</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7852845</wfw:comment><description>&lt;p&gt;Part of creating a multithreading program is understanding which threads objects live on.&amp;#160; Seems simple enough and typically is.&amp;#160; However it's nice to insert guarantees to match the design. &lt;/p&gt;  &lt;p&gt;One type of threading model is for objects or subsets of methods in an object to have an affinity to a particular thread.&amp;#160; Meaning that those methods can only be validly called on a particular thread and no other.&amp;#160; I create a small helper object to help validate this affinity.&amp;#160; &lt;/p&gt;  &lt;p&gt;Simple, but gets the job done. &lt;/p&gt;  &lt;pre class="code"&gt;    [&lt;span style="color: rgb(43,145,175)"&gt;Immutable&lt;/span&gt;]
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;sealed&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ThreadAffinity
&lt;/span&gt;    {
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;readonly&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_threadId;

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; ThreadAffinity()
        {
            m_threadId = &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.CurrentThread.ManagedThreadId;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Check()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.CurrentThread.ManagedThreadId != m_threadId)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; msg = &lt;span style="color: rgb(43,145,175)"&gt;String&lt;/span&gt;.Format(
                    &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;Call to class with affinity to thread {0} detected from thread {1}.&amp;quot;&lt;/span&gt;,
                    m_threadId,
                    &lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.CurrentThread.ManagedThreadId);
                &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt;(msg);
            }
        }
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7852845" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category></item><item><title>Building a Future which returns no Value</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/18/building-a-future-which-returns-no-value.aspx</link><pubDate>Tue, 19 Feb 2008 00:15:52 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7780383</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7780383.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7780383</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7780383</wfw:comment><description>&lt;p&gt;In addition to &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/13/building-future-t.aspx"&gt;Future&amp;lt;T&amp;gt;&lt;/a&gt; there is also the concept of Futures that don't return any values.&amp;#160; Instead the perform the operation and return.&amp;#160; Because there is no additional data to pass between the threads building an Empty Future is fairly straight forward.&lt;/p&gt;  &lt;p&gt;The biggest decision is how to declare it.&amp;#160; EmptyFuture exposes no new accessible methods or properties above what &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/12/building-the-base-future.aspx"&gt;Future&lt;/a&gt; already exposes.&amp;#160; If a class doesn't provide any additional behavior is there any reason to expose it?&amp;#160; In this case I think not.&amp;#160; Therefore it will be declared as a private inner class of &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/12/building-the-base-future.aspx"&gt;Future&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;Yes this makes it impossible to directly create from a user perspective.&amp;#160; You could also make a good argument that creation is new behavior and therefore EmptyFuture should be exposed.&amp;#160; However for Future's, as with other generic classes, I prefer static factory methods for creation.&amp;#160; It allows the user to take advantage of type inference as much as possible.&lt;/p&gt;  &lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;EmptyFuture&lt;/span&gt; : &lt;span style="color: rgb(43,145,175)"&gt;Future
&lt;/span&gt;        {
            &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt; m_action;

            &lt;span style="color: rgb(0,0,255)"&gt;internal&lt;/span&gt; EmptyFuture(&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt; action)
            {
                m_action = action;
            }

            &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;override&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunCore()
            {
                m_action();
            }

        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Next we'll go over the creation of the factory methods to create this and Future&amp;lt;T&amp;gt;.&amp;#160; &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7780383" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</category></item><item><title>Building Future&lt;T&gt;</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/13/building-future-t.aspx</link><pubDate>Wed, 13 Feb 2008 18:16:43 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7676087</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7676087.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7676087</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7676087</wfw:comment><description>&lt;p&gt;The &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/12/building-the-base-future.aspx"&gt;last post&lt;/a&gt; dealt with building the base Future class.&amp;#160; Now we'll build the child class used to run &lt;a href="http://msdn2.microsoft.com/en-us/library/bb534960.aspx"&gt;Func&amp;lt;TResult&amp;gt;&lt;/a&gt;'s.&amp;#160; &lt;/p&gt;  &lt;p&gt;The basic implementation is straight forward.&amp;#160; The class will run a delegate typed to &lt;a href="http://msdn2.microsoft.com/en-us/library/bb534960.aspx"&gt;Func&amp;lt;TResult&amp;gt;&lt;/a&gt; in the override of RunCore.&amp;#160; The trickiest part is how to store the value.&amp;#160; The value is set on one thread and read off of another.&amp;#160; &lt;/p&gt;  &lt;p&gt;When a value is read and written on multiple threads there are a couple of options for synchronization between threads.&amp;#160; One of them is to use the volatile keyword for the data.&amp;#160; This forces the CLR to read the value from memory every time and prevents caching issues between threads.&amp;#160; Unfortunately volatile cannot be applied to an unbounded generic.&amp;#160; &lt;/p&gt;  &lt;p&gt;To get around this I've declared the value to be of type object.&amp;#160; Whenever the value is accessed by the user of Future&amp;lt;T&amp;gt; a cast is applied to the appropriate type.&amp;#160; This incurs boxing overhead but it's minimal and in the typical case will be limited to one box and unbox per value type.&amp;#160; &lt;/p&gt;  &lt;p&gt;In addition Future&amp;lt;T&amp;gt; adds one new method; Wait;&amp;#160; It's a combination of calling WaitEmpty followed by returning the value.&amp;#160; &lt;/p&gt;  &lt;p&gt;In a perfect world WaitEmpty in Future would really be called Wait and be virtual.&amp;#160; Future&amp;lt;T&amp;gt; would override the method and alter the return type to be T.&amp;#160; Unfortunately C#/VB don't support covariant return types on virtual method overrides so it's not possible.&amp;#160; Truthfully I don't know if this is a C#/VB limitation or a CLR one.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43,145,175)"&gt;Future
&lt;/span&gt;    {
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; m_function;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;volatile&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; m_value;

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; T Value
        {
            &lt;span style="color: rgb(0,0,255)"&gt;get&lt;/span&gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Wait(); }
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; Future(&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; function)
        {
            m_function = function;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; T Wait()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;.WaitEmpty();
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; (T)m_value;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;override&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunCore()
        {
            m_value = m_function();
        }

    }&lt;/pre&gt;
Next time I'll go over the implementation of Futures which return no values.&amp;#160; &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7676087" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</category></item><item><title>Building the Base Future</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/12/building-the-base-future.aspx</link><pubDate>Tue, 12 Feb 2008 18:48:53 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7645682</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7645682.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7645682</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7645682</wfw:comment><description>&lt;p&gt;In the end there are two basic types of Future implementations you can use.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Futures which return no values &lt;/li&gt;    &lt;li&gt;Futures which return a value &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The rest of the behavior and shape of the Future is the same and screams for a pattern of sorts.&amp;#160; I've found the best way to implement this behavior is through an inheritance pattern.&amp;#160; The base class is name of course Future.&amp;#160; It's purpose is to provide a common way in which to schedule the invocation of a delegate, &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/11/dealing-with-exceptions-in-a-future.aspx"&gt;handle exceptions&lt;/a&gt;, wait for the completion of such delegate and enforce certain contracts such as not running the future more than once.&lt;/p&gt;  &lt;p&gt;At the core it only needs a few members.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/04/the-first-part-of-building-a-future-is-waiting.aspx"&gt;ActiveOperation&lt;/a&gt; m_operation which is used to implement the waiting portion &lt;/li&gt;    &lt;li&gt;int m_run used to ensure a future is not run twice &lt;/li&gt;    &lt;li&gt;Exception m_error to record any exceptions thrown by running the delegate &lt;/li&gt; &lt;/ol&gt;  &lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ActiveOperation&lt;/span&gt; m_operation = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ActiveOperation&lt;/span&gt;();
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_run;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; m_error;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;It has one public property to determine whether or not a Future has completed.&amp;#160; It's a proxy into m_operation&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; HasCompleted
        {
            &lt;span style="color: rgb(0,0,255)"&gt;get&lt;/span&gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_operation.HasCompleted; }
        }&lt;/pre&gt;

&lt;p&gt;By using m_operation to deal with Waiting, the majority of WaitEmpty can be proxied to m_operation as well.&amp;#160; The only additional work needed is to deal with Exceptions.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; WaitEmpty()
        {
            m_operation.Wait();
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (m_error != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FutureException&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;Error occurred running future&amp;quot;&lt;/span&gt;, m_error);
            }
        }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The only behavior a child class needs is a place to invoke the delegate.&amp;#160; A single abstract method is provided to allow implement this behavior.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;abstract&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunCore();&lt;/pre&gt;

&lt;p&gt;Before calling this method the base Future class must make sure that all of the contracts are met.&amp;#160; This is implemented through a wrapper method around RunCore.&amp;#160; It is the only method that calls RunCore directly.&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunWrapper()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (0 != &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.CompareExchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_run, 1, 0))
            {
                &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;Future is already run&amp;quot;&lt;/span&gt;);
            }

            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                RunCore();
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_error, ex);
            }
            &lt;span style="color: rgb(0,0,255)"&gt;finally
&lt;/span&gt;            {
                m_operation.Completed();
            }
        }&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;It's very important that m_operation is signalled as completed after exception handling occurs.&amp;#160; The setting or not setting of m_error is the only way we know if an exception occurred when waiting.&amp;#160; If we do this in the opposite order it's possible for WaitEmpty() to complete before the exception is set and hence miss the error.&lt;/p&gt;

&lt;p&gt;Lastly is the code to actually run the Future.&amp;#160; There are two ways to run the Future (more can be added).&amp;#160; &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Asynchronously through the ThreadPool.&amp;#160; This is the more common case. &lt;/li&gt;

  &lt;li&gt;Synchronously on the same thread.&amp;#160; This will mainly be used to implement such operations as methods in Active Objects. &lt;/li&gt;
&lt;/ol&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Run()
        {
            RunWrapper();
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; RunInThreadPool()
        {
            &lt;span style="color: rgb(43,145,175)"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem((x) =&amp;gt; RunWrapper());
        }&lt;/pre&gt;
This leaves us with a base class implementation for Future's.&amp;#160; Next we'll implement Future which return values.&amp;#160; &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7645682" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</category></item><item><title>Push Enumerators</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/05/push-enumerators.aspx</link><pubDate>Tue, 05 Feb 2008 20:26:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7470714</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7470714.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7470714</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7470714</wfw:comment><description>&lt;p&gt;If you read Jon Skeet's blog you'll notice he's been playing around lately with "push" style enumerators.&amp;nbsp; Push enumerators are the concept of "we'll tell you when we're ready".&amp;nbsp; This is different from IEnumerator&amp;lt;T&amp;gt; which is more of a pull; "ask me if I have more data model".&lt;/p&gt; &lt;p&gt;His latest idea is an interface based approach called IDataProducer&amp;lt;T&amp;gt;.&amp;nbsp; The full post can be found here.&amp;nbsp; &lt;a title="http://msmvps.com/blogs/jon.skeet/archive/2007/11/29/group-pipelining-returns-new-and-improved-design.aspx" href="http://msmvps.com/blogs/jon.skeet/archive/2007/11/29/group-pipelining-returns-new-and-improved-design.aspx"&gt;http://msmvps.com/blogs/jon.skeet/archive/2007/11/29/group-pipelining-returns-new-and-improved-design.aspx&lt;/a&gt;.&amp;nbsp; &lt;/p&gt; &lt;p&gt;After reading the post I decided to try and bridge the gap between the worlds of Push/Pull models by defining an enumerator over an IDataProducer&amp;lt;T&amp;gt;.&amp;nbsp; Integration with the existing paradigms is extremely important for the adoption of a new technology.&amp;nbsp; Eventually you'll eventually want to pass your asynchronous enumerator off to an API requiring IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Since we are implementing a pull model it will revolve around asking for more data and blocking until such data is available.&amp;nbsp; To implement the wait functionality I've used an AutoResetEvent to provide signaling between threads.&amp;nbsp; One of the tricky aspects is that IDataProducer&amp;lt;T&amp;gt; can live on any thread and hence any thread can be raising the various events.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Below is my first attempt at getting it to work.&amp;nbsp; It has a couple of defects.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;I don't dispose of the AutoResetEvent.&amp;nbsp; Reason being that it's possible for a consumer of IEnumerable&amp;lt;T&amp;gt; to only consume part of the data.&amp;nbsp; If they only consume half of the data and then dispose of the EnumerableDataProducer and another event comes I'll be accessing a disposed WaitHandle.&amp;nbsp; You can work around this but I wanted to keep it simpler for now.&lt;/li&gt; &lt;li&gt;It's not Reset-able.&amp;nbsp; The generated IEnumerator&amp;lt;T&amp;gt; throws a NotSupportedException anyway but we'd have to do a bit of work to make this resetable.&amp;nbsp; &lt;/li&gt;&lt;/ol&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;EnumerableDataProducer&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43,145,175)"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;
    {
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; m_lock = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt;();
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; m_finished;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;AutoResetEvent&lt;/span&gt; m_event = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;AutoResetEvent&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;);
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt; m_queue = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt;();

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; EnumerableDataProducer(&lt;span style="color: rgb(43,145,175)"&gt;IDataProducer&lt;/span&gt;&amp;lt;T&amp;gt; producer)
        {
            producer.DataProduced += &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;(OnDataProdecuded);
            producer.EndOfData += &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt;(OnEndOfData);
        }

        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; OnDataProdecuded(T obj)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;lock&lt;/span&gt; (m_lock)
            {
                m_queue.Enqueue(obj);
            }

            m_event.Set();
        }

        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; OnEndOfData()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;lock&lt;/span&gt; (m_lock)
            {
                m_finished = &lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;;
            }
            m_event.Set();
        }

&lt;span style="color: rgb(0,0,255)"&gt;        #region&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Members

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; GetEnumerator()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;while&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; needWait = &lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;;
                &lt;span style="color: rgb(0,0,255)"&gt;lock&lt;/span&gt; (m_lock)
                {
                    &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (m_finished)
                    {
                        &lt;span style="color: rgb(0,0,255)"&gt;break&lt;/span&gt;;
                    }

                    &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (m_queue.Count &amp;gt; 0)
                    {
                        &lt;span style="color: rgb(0,0,255)"&gt;yield&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_queue.Dequeue();
                    }
                    &lt;span style="color: rgb(0,0,255)"&gt;else
&lt;/span&gt;                    {
                        needWait = &lt;span style="color: rgb(0,0,255)"&gt;true&lt;/span&gt;;
                    }
                }

                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (needWait)
                {
                    m_event.WaitOne();
                }
            }
        }

&lt;span style="color: rgb(0,0,255)"&gt;        #endregion

        #region&lt;/span&gt; IEnumerable Members

        System.Collections.&lt;span style="color: rgb(43,145,175)"&gt;IEnumerator&lt;/span&gt; System.Collections.&lt;span style="color: rgb(43,145,175)"&gt;IEnumerable&lt;/span&gt;.GetEnumerator()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; GetEnumerator();
        }

&lt;span style="color: rgb(0,0,255)"&gt;        #endregion
&lt;/span&gt;    }
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7470714" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category></item><item><title>The first part of building a Future is ... Waiting</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/04/the-first-part-of-building-a-future-is-waiting.aspx</link><pubDate>Mon, 04 Feb 2008 15:04:41 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7438992</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7438992.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7438992</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7438992</wfw:comment><description>&lt;p&gt;Future's are a great abstraction for asynchronous programming.&amp;nbsp; One of the items making them so good is the easy manner in which you can declare one and wait for it to finish.&amp;nbsp; The idea is to allow for many futures to be declared with as little overhead as possible.&amp;nbsp; In order to do so you need to define an efficient way of waiting.&lt;/p&gt; &lt;p&gt;Normally when you need to wait on operations between two threads to complete you use a Thread.Join call or a form of a WaitHandle.&amp;nbsp; I tend to prefer a &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.manualresetevent.aspx"&gt;ManualResetEvent&lt;/a&gt;.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Unfortunately a &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.manualresetevent.aspx"&gt;ManualResetEvent&lt;/a&gt; is not free and under the hood will allocate a kernel handle.&amp;nbsp; There are a lot of handles to go around and while unlikely that a program purely using futures will allocate too many handles, you may be running with other code that is handle hungry.&amp;nbsp; &lt;/p&gt; &lt;p&gt;In addition several cases do not need a handle.&amp;nbsp; For instance in the below code, if the commented out section takes longer than the future to complete then why do you even need wait handle of any sort?&lt;/p&gt;&lt;pre class="code"&gt;           &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; d = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; CallASimpleFunction);
            &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            d.Wait();&lt;/pre&gt;
&lt;p&gt;Therefore the first step is to define an efficient waiting mechanism.&amp;nbsp; I call it an ActiveOperation.&amp;nbsp; It provides 3 basic methods; HasCompleted, Completed and Wait.&amp;nbsp; It optimizes for trying to not created a WaitEvent unless actually necessary.&amp;nbsp; It has two member variables.&amp;nbsp; An int for completion check and a &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.manualresetevent.aspx"&gt;ManualResetEvent&lt;/a&gt; to be used for shared waiting when necessary.&amp;nbsp; Notice that m_hasCompleted is not volatile, instead all writes use a Interlocked operation to ensure it is propagated between threads.&lt;/p&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; m_hasCompleted;
        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt; m_waitEvent;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;HasCompleted is straightforward.&lt;/p&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; HasCompleted
        {
            &lt;span style="color: rgb(0,0,255)"&gt;get&lt;/span&gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_hasCompleted == 1; }
        }&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Completed is a little bit trickier.&amp;nbsp; It has to deal with a couple of cases.&amp;nbsp; &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Another thread already called Completed.&amp;nbsp; &lt;li&gt;Completed called before another thread calls Wait.&amp;nbsp; &lt;li&gt;Completed called while or after another thread calls Wait.&amp;nbsp;&amp;nbsp; &lt;/li&gt;&lt;/ol&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Completed()
        {
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (0 == &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.CompareExchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_hasCompleted, 1, 0))
            {
                &lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt; mre = m_waitEvent;
                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (mre != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
                {
                    &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;                    {
                        mre.Set();
                    }
                    &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;ObjectDisposedException&lt;/span&gt;)
                    {
                        &lt;span style="color: rgb(0,128,0)"&gt;// If another thread is in Wait at the same time and sees the completed flag
&lt;/span&gt;                        &lt;span style="color: rgb(0,128,0)"&gt;// it may dispose of the shared event.  In this case there is no need to signal
&lt;/span&gt;                        &lt;span style="color: rgb(0,128,0)"&gt;// just return.
&lt;/span&gt;                    }
                }
            }
        }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Wait is the trickiest one.&amp;nbsp; It has the following cases to deal with&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;HasCompleted already set 
&lt;li&gt;Second or later thread to call Wait and needs to wait on m_waitEvent 
&lt;li&gt;While attempting to create m_waitEvent, another thread in Wait finishes first. 
&lt;li&gt;Thread successfully creates and owns the shared m_waitEvent variable before Completed() is called. 
&lt;li&gt;During the creation of m_waitEvent, another thread calls Completed() in which case there is no guarantee that m_waitEvent will be signaled. &lt;/li&gt;&lt;/ol&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Wait()
        {
            &lt;span style="color: rgb(0,128,0)"&gt;// Case 1
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (HasCompleted)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt;;
            }

            &lt;span style="color: rgb(0,128,0)"&gt;// Case 2
&lt;/span&gt;            &lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt; sharedEvent = m_waitEvent;
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (sharedEvent != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
            {
                WaitOnEvent(sharedEvent);
            }

            &lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt; created = &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;;
            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                created = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;false&lt;/span&gt;);
                sharedEvent = &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.CompareExchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_waitEvent, created, &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;);
                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt; != sharedEvent)
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// Case 3.  Another thread got here first and it's created is now the shared event.  Wait
&lt;/span&gt;                    &lt;span style="color: rgb(0,128,0)"&gt;// on that event
&lt;/span&gt;                    WaitOnEvent(sharedEvent);
                }
                &lt;span style="color: rgb(0,0,255)"&gt;else&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (HasCompleted)
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// Case 5. In between the time we checked for completion and created the event a completion
&lt;/span&gt;                    &lt;span style="color: rgb(0,128,0)"&gt;// occurred.  Returning will dispose of m_waitEvent and force other threads Wait to complete 
&lt;/span&gt;                    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt;;
                }
                &lt;span style="color: rgb(0,0,255)"&gt;else
&lt;/span&gt;                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// Case 4. 
&lt;/span&gt;                    WaitOnEvent(created);
                }
            }
            &lt;span style="color: rgb(0,0,255)"&gt;finally
&lt;/span&gt;            {
                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (created != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt; )
                {
                    &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; ( sharedEvent == &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
                    {
                        &lt;span style="color: rgb(43,145,175)"&gt;Interlocked&lt;/span&gt;.Exchange(&lt;span style="color: rgb(0,0,255)"&gt;ref&lt;/span&gt; m_waitEvent, &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;);
                    }

                    created.Close();
                }
            }
        }

        &lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; WaitOnEvent(&lt;span style="color: rgb(43,145,175)"&gt;ManualResetEvent&lt;/span&gt; mre)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                mre.WaitOne();
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;ObjectDisposedException&lt;/span&gt;)
            {

            }
        }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Now you have one of the basic building blocks of Futures.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7438992" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</category></item><item><title>Active Objects and Futures</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/28/active-objects-and-futures.aspx</link><pubDate>Tue, 29 Jan 2008 07:57:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7298431</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7298431.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7298431</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7298431</wfw:comment><description>&lt;p&gt;Herb Sutter gave one of my favorite and inspiring presentations.&amp;#160; It is called &amp;quot;The Free Lunch is Over&amp;quot;.&amp;#160; The original article can be found &lt;a href="http://www.gotw.ca/publications/concurrency-ddj.htm"&gt;here&lt;/a&gt;.&amp;#160; My first encounter though came from his &lt;a href="http://www.pluralsight.com/blogs/hsutter/archive/2005/10/25/15903.aspx"&gt;PDC presentation&lt;/a&gt; and highly recommend viewing that as well.&lt;/p&gt;  &lt;p&gt;The part that interested me the most about the talk was two new threading abstractions I hadn't encountered before.&amp;#160; Future's and ActiveObjects.&amp;#160; One of the basic premise is that concurrency should be grep`able and somewhat declarative.&amp;#160; The act of calling a method on a background thread and later waiting for it to complete should be simple, not complicated.&amp;#160; &lt;/p&gt;  &lt;p&gt;Asynchronous programming is one of my favorite aspects of computing.&amp;#160; What interests me the most is how asynchronous programming can be useful for UI.&amp;#160; My biggest pet peeve is when UI hangs because an operation call, or network operation takes too long.&amp;#160; Why not make multi-threading easy and give users a way to cancel out of these operations???&amp;#160; Or start loading on the background thread instead of waiting for the user to perform a specific.&amp;#160; Hopefully over the next month or so I'll lay out some utilities and classes building on Futures and Active Objects that will do precisely this.&lt;/p&gt;  &lt;p&gt;Future's are actions where work can be done now, but the result is not needed until a future time.&amp;#160; Work occurs on a separate thread and the results can be easily joined once work is complete.&lt;/p&gt;  &lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; LongCalculation());
            &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; result = f.Wait();&lt;/pre&gt;

&lt;p&gt;Future's are now exposed via the &lt;a href="http://blogs.msdn.com/pfxteam/archive/2007/11/29/6558413.aspx"&gt;Parallel Extension&lt;/a&gt; team's work.&amp;#160; You can download the CTP off of their web site and get to work. &lt;/p&gt;

&lt;p&gt;ActiveObjects are objects which only expose Asynchronous functions where the return value is exposed as a Future.&amp;#160; So instead of &lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; GetName()&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;You would have&lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;&amp;gt; GetName()&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;An ActiveObject essentially lives on or owns a thread.&amp;#160; All operations are queued up and processed one at a time.&amp;#160; Since only one action at a time can be executing the object internals don't have to use locks or consider many types of race conditions.&amp;#160; In fact if your return types are immutable a great many threading concerns go out the window.&amp;#160; Yet all of the calls are inherently asynchronous so callers can get the result only when they are needed.&amp;#160; The best of both worlds.&amp;#160; &lt;/p&gt;

&lt;p&gt;Both of these provide significant advantages over the &amp;quot;lock before use&amp;quot; patterns.&amp;#160; In my experience I find these to be hard to maintain and lead to difficult to track down bugs.&amp;#160; I can't tell you how many times I've gone through someone else's code, or even my own, and wondered ...&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Did they forget to lock here or is this an optimization?&lt;/li&gt;

  &lt;li&gt;Is a join needed here or can these terminate at separate times?&lt;/li&gt;

  &lt;li&gt;OK I need to touch that variable, can it be accessed in multiple threads or is it safe? &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Futures/Active Objects on the other hand are a bit more declarative and straight forward to understand than plain old locks.&amp;#160; They allow you to do away with many uses of plain old locking.&amp;#160; Don't confuse this with me saying they are a cure all for threading.&amp;#160; They're not.&amp;#160; But in my experiences I've found them to be a significant upgrade.&amp;#160; &lt;/p&gt;

&lt;p&gt;Over the next month or so I'll be laying out the design for a basic ActiveObject implementation.&amp;#160; We will likely have to deviate off of the Parrallel Extension work to get certain behaviors but the concepts map well.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7298431" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Active+Object/default.aspx">Active Object</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</category></item><item><title>Tuples Part 7: Mutable Tuples</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/23/tuples-part-7-mutable-tuples.aspx</link><pubDate>Wed, 23 Jan 2008 10:56:19 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7206269</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7206269.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7206269</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7206269</wfw:comment><description>&lt;p&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/22/tuples-part-6-comparing.aspx"&gt;Part 6&lt;/a&gt; left us with comparable tuples.&amp;#160; At this point, the Tuple class is functionally complete.&amp;#160; There will be a little more done with the debugability and overall fit into larger projects.&amp;#160; But otherwise it is sound.&amp;#160; &lt;/p&gt;  &lt;p&gt;Now the focus shifts to generating mutable tuples.&amp;#160; Immutability is nice for threading, memoization, etc ...&amp;#160; However it's not always practical to use immutable objects.&amp;#160; Often an algorithm does not benefit from immutability and lends itself to a more mutable type.&amp;#160; &lt;/p&gt;  &lt;p&gt;Mutable tuples behave like a Tuple in every other way except that they're ... mutable.&amp;#160; This includes implementing interfaces as well as inheritance structure.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;sealed&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt; : 
    &lt;span style="color: rgb(43,145,175)"&gt;ITuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IEquatable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IComparable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IComparable
&lt;/span&gt;{&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As such the script already used will be sufficient to generate mutable classes in addition to the ones its already doing.&amp;#160; The majority of the code difference is just in the naming of the classes.&amp;#160; The only functional differences exist in the properties and indexer.&amp;#160; Both of these add a setter method.&amp;#160; Below is the modified code for generating the property and indexer.&amp;#160; &lt;/p&gt;

&lt;p&gt;function script:Gen-TupleAccess
  &lt;br /&gt;{

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; param ( [int] $count = $(throw &amp;quot;Need a count&amp;quot;), [bool]$mutable )

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;public int Count { get { return $count; } }&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;public object this[int index] { get { switch (index){ &amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; 0..($count-1) | %{ &amp;quot;case $($_): return m_$($lowerList[$_]);&amp;quot; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;default: throw new InvalidOperationException(&amp;quot;&amp;quot;Bad Index&amp;quot;&amp;quot;);&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;} }&amp;quot; &lt;/p&gt;

&lt;p&gt;&amp;#160;&amp;#160;&amp;#160; if ( $mutable )
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;set { switch (index) {&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0..($count-1) | %{ &amp;quot;case $($_): m_$($lowerList[$_]) = (T$($upperList[$_]))value; break;&amp;quot; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;default: throw new InvalidOperationException(&amp;quot;&amp;quot;Bad Index&amp;quot;&amp;quot;);&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;} } &amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;}&amp;quot;

  &lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;function script:Gen-Property
  &lt;br /&gt;{

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; param ( [int] $index&amp;#160; = $(throw &amp;quot;Need an index&amp;quot;), [bool]$mutable = $false) &lt;/p&gt;

&lt;p&gt;&amp;#160;&amp;#160;&amp;#160; if (-not $mutable )
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {

  &lt;br /&gt;@&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private readonly T{0} m_{1};

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public T{0} {0} {{ get {{ return m_{1}; }} }} &lt;/p&gt;

&lt;p&gt;&amp;quot;@ -f $upperList[$index],$lowerList[$index]
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; else

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {

  &lt;br /&gt;@&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private T{0} m_{1};

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public T{0} {0} {{ get {{ return m_{1}; }} set {{ m_{1} = value; }} }} &lt;/p&gt;

&lt;p&gt;&amp;quot;@ -f $upperList[$index],$lowerList[$index]
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;Now creating a mutable tuple is the same as the immutable tuple with just a name tweak.&lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; t1 = &lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;.Create(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, 42);
            t1.A = &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;again&amp;quot;&lt;/span&gt;;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7206269" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Tuple/default.aspx">Tuple</category></item></channel></rss>