<?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 : Futures</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx</link><description>Tags: Futures</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Factory Methods for Futures</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/23/factory-methods-for-futures.aspx</link><pubDate>Sun, 24 Feb 2008 04:35:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7866781</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7866781.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7866781</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7866781</wfw:comment><description>&lt;p&gt;Like most generic classes, I prefer to create Future instances through static factory methods which allows me to take maximum advantage of type inference.&amp;nbsp; &lt;/p&gt; &lt;p&gt;In addition to the 2 straight forward declaration of Func&amp;lt;T&amp;gt; and Action, the methods will include overloads which take in Func&amp;lt;T&amp;gt; with varying numbers of arguments.&amp;nbsp; The overloads will cury the arguments and create a Func&amp;lt;T&amp;gt; taking no arguments.&amp;nbsp; This is a great convenience to the user and takes little extra code to implement.&amp;nbsp; &lt;/p&gt; &lt;p&gt;In addition because we don't expose the EmptyFuture class directly we need to provide a factory method to create it in a non-run state.&amp;nbsp; Otherwise we are forcing the EmptyFuture to always be created and run in the ThreadPool.&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;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; Create(&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(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;EmptyFuture&lt;/span&gt;(action);
            f.RunInThreadPool();
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }

        &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; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; Create&amp;lt;TArg1&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt;&amp;lt;TArg1&amp;gt; action, TArg1 arg1)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Create(() =&amp;gt; action(arg1));
        }

        &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; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt; Create&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(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt;(func);
            f.RunInThreadPool();
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; f;
        }

        &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; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;TReturn&amp;gt; Create&amp;lt;TArg1,TReturn&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;TArg1, TReturn&amp;gt; func, TArg1 arg1)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Create(() =&amp;gt; func(arg1));
        }

        &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; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;&amp;lt;T&amp;gt; CreateNoRun&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;return&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;Future&lt;/span&gt;&amp;lt;T&amp;gt;(func);
        }

        &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; &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt; CreateNoRun(&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt; action)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&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;EmptyFuture&lt;/span&gt;(action);
        }
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&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=7866781" 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/Futures/default.aspx">Futures</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>Dealing with Exceptions in a Future</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/11/dealing-with-exceptions-in-a-future.aspx</link><pubDate>Mon, 11 Feb 2008 19:36:22 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7614564</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>7</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7614564.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7614564</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7614564</wfw:comment><description>&lt;p&gt;Besides waiting, the another important issue when dealing with Futures is how to deal with exceptions thrown by the user specified code.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 1: Ignore the Exception&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Don't take any actions in the future code and force users to write exception free code.&amp;#160; IMHO this is not the best way to approach the problem.&amp;#160; The code will be running in the thread pool and unhandled exceptions in the thread pool result in the taking down of an appdomain/process.&amp;#160; In addition Futures are designed to be simple.&amp;#160; Adding a try/catch around every lambda is not practical and/or readable.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 2: Catch and Swallow&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Catch the exception on the background thread and swallow it.&amp;#160; Silently failing is in many cases worse than actually crashing.&amp;#160; Behavior will become flaky and the user/developer won't have any indication there is an error.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 3: Re-throw the Exception when Wait is called&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Catch and save the exception when it occurs on the background thread.&amp;#160; Then when Wait() is called on a Future re-throw the exception.&amp;#160; This makes exception handled deterministic.&lt;/p&gt;  &lt;p&gt;It's also very similar to the exception handling semantics of calling a method.&amp;#160; The only difference is that users must handle the exception at the point of method completion vs invocation.&amp;#160; For synchronous methods this is just the same point.&lt;/p&gt;  &lt;p&gt;The big downside to this approach is the stack trace information is lost from the exception.&amp;#160; Re-throwing will instead add the stack trace at the point of the re-throw.&amp;#160; Not having stack trace information makes it very difficult to actually track down the source of an error.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 4: Re-throw a new Exception when Wait is called &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This is very similar to Option #3.&amp;#160; The only difference is when the user calls Wait, throw a new exception and make the original exception an inner exception of the new one.&amp;#160; We'll call this exception FutureException.&amp;#160; This has the advantages of option 3 and in addition will preserve the stack trace information from the original exception.&lt;/p&gt;  &lt;p&gt;There is a downside to this approach though.&amp;#160; Users can no longer have different catch blocks to handle the different types of exceptions that can be thrown.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; SomeOperation());
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;IOException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            }&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Instead the user can only catch a Future exception and examine the inner result to take corrective action.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; SomeOperation());
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;FutureException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; type = ex.InnerException.GetType();
                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (type == &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;IOException&lt;/span&gt;))
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;                }
                &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; (type == &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt;))
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;                }
            }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This doesn't actually limit any functionality but users may find the syntax uncomfortable.&amp;#160; VB users can still do exception filtering but this is not at option for C# users.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Try
&lt;/span&gt;            Future.Create(&lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt;() SomeOperation())
        &lt;span style="color: rgb(0,0,255)"&gt;Catch&lt;/span&gt; ex &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Exception &lt;span style="color: rgb(0,0,255)"&gt;When&lt;/span&gt; ex.InnerException.GetType() &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;GetType&lt;/span&gt;(IOException)

        &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Try&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The FutureException class is straight forward.&amp;#160; A simple implementation of the exception snippet will do the trick. &lt;/p&gt;

&lt;pre class="code"&gt;    [&lt;span style="color: rgb(0,0,255)"&gt;global&lt;/span&gt;::System.&lt;span style="color: rgb(43,145,175)"&gt;Serializable&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;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FutureException&lt;/span&gt; : &lt;span style="color: rgb(43,145,175)"&gt;Exception
&lt;/span&gt;    {


        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException() { }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; message) : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(message) { }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; message, &lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; inner) : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(message, inner) { }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; FutureException(
          System.Runtime.Serialization.&lt;span style="color: rgb(43,145,175)"&gt;SerializationInfo&lt;/span&gt; info,
          System.Runtime.Serialization.&lt;span style="color: rgb(43,145,175)"&gt;StreamingContext&lt;/span&gt; context)
            : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(info, context) { }
    }&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=7614564" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Futures/default.aspx">Futures</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></channel></rss>