<?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>Parallel Programming with .NET</title><link>http://blogs.msdn.com/b/pfxteam/</link><description>All about System.Threading, System.Threading.Tasks, System.Collections.Concurrent, System.Linq, and more...</description><dc:language>en-US</dc:language><generator>Telligent Community 5.6.583.20496 (Build: 5.6.583.20496)</generator><item><title>Potential pitfalls to avoid when passing around async lambdas</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx</link><pubDate>Wed, 08 Feb 2012 17:02:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10265476</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10265476</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10265476</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx#comments</comments><description>&lt;p&gt;One of the really useful capabilities of the new async methods feature in C# and Visual Basic is the ability to write async lambdas and anonymous methods (from here on in this post, I’ll refer to both of these as async lambdas, since the discussion applies equally to both).&amp;#160; This allows you to easily get a delegate to represent an asynchronous operation, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#4bacc6"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#4bacc6"&gt;Uri&lt;/font&gt;,&lt;font color="#4bacc6"&gt;Task&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;&amp;gt; getContentsLowerCaseAsync = &lt;font color="#0000ff"&gt;async&lt;/font&gt; url =&amp;gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;string&lt;/font&gt; contents = &lt;font color="#0000ff"&gt;await&lt;/font&gt; DownloadString(url);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; contents.ToLower();        &lt;br /&gt;};&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Async methods in C# and Visual Basic can return void, Task, or Task&amp;lt;TResult&amp;gt;, which means they can be mapped to delegates that return void, Task, or Task&amp;lt;TResult&amp;gt;.&amp;#160; This is very powerful, but it can also lead to subtle bugs if you’re not careful.&lt;/p&gt;  &lt;p&gt;Most methods today that accept as a parameter a delegate that returns void (e.g. Action, Action&amp;lt;T&amp;gt;, etc.) expect the work of that delegate to be completed by the time the delegate completes.&amp;#160; As a simple example, consider a timing helper function, whose job it is to time how long a particular piece of code takes to execute:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;&lt;font size="2"&gt;&lt;font color="#0000ff"&gt;public static double&lt;/font&gt; Time(&lt;font color="#4bacc6"&gt;Action&lt;/font&gt; action, &lt;font color="#0000ff"&gt;int&lt;/font&gt; iters=10)          &lt;br /&gt;{          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; sw = &lt;font color="#4bacc6"&gt;Stopwatch&lt;/font&gt;.StartNew();          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for&lt;/font&gt;(int i=0; i&amp;lt;iters; i++) action();          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; sw.Elapsed.TotalSeconds / iters;          &lt;br /&gt;}&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With this function, if I then run the following code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;&lt;font size="2"&gt;&lt;font color="#0000ff"&gt;static void&lt;/font&gt; Main()          &lt;br /&gt;{          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;double&lt;/font&gt; secs = Time(() =&amp;gt;          &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; &lt;font color="#4bacc6"&gt;Thread&lt;/font&gt;.Sleep(1000);          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Console&lt;/font&gt;.WriteLine(&amp;quot;Seconds: {0:F7}&amp;quot;, secs);          &lt;br /&gt;}&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I see this written out to the console:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;Seconds: 0.9999956       &lt;br /&gt;Press any key to continue . . .&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That’s what I’d expect: we asked to sleep for one second, and that’s almost exactly what the timing showed.&amp;#160; But now consider an alternate piece of code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;&lt;font size="2"&gt;&lt;font color="#0000ff"&gt;static void&lt;/font&gt; Main()          &lt;br /&gt;{          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;double&lt;/font&gt; secs = Time(&lt;font color="#0000ff"&gt;async&lt;/font&gt; () =&amp;gt;          &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; &lt;font color="#0000ff"&gt;await&lt;/font&gt; &lt;font color="#4bacc6"&gt;Task&lt;/font&gt;.Delay(1000);          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#c0504d"&gt;&amp;quot;Seconds: {0:F7}&amp;quot;&lt;/font&gt;, secs);          &lt;br /&gt;}&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When I run this, I see the following written out to the console:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;Seconds: 0.0000341       &lt;br /&gt;Press any key to continue . . .&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Huh? Here we have an async method that’s awaiting a Task that won’t complete for a second, so this asynchronous method’s execution should also be at least a second, and yet the timer is telling us that it took only 34 microseconds?&amp;#160; What’s going on?&lt;/p&gt;  &lt;p&gt;To understand this effect, we need to remember how async methods operate.&amp;#160; When you invoke an async method, it starts running synchronously.&amp;#160; If the method doesn’t have any awaits in it, or if all of the awaits in the method are on awaitables that are already completed by the time they’re awaited, then the method will run entirely synchronously.&amp;#160; However, when the method encounters the first await that yields, the async method returns.&amp;#160; In the case of an async method that returns a Task or a Task&amp;lt;TResult&amp;gt;, the method at this point returns the Task or Task&amp;lt;TResult&amp;gt; that represents the async method’s execution, and the caller can use that task to wait synchronous (e.g. Wait()) or asynchronously (e.g. await, ContinueWith) for the method to asynchronously complete.&amp;#160; In the case of a void method, though, no handle is handed back.&amp;#160; Async void methods are thus often referred to as “fire and forget.”&lt;/p&gt;  &lt;p&gt;Now with that background, consider what’s happening with our timing function.&amp;#160; Our Time method accepts an Action, so the compiler is going to map our “async () =&amp;gt; { … }” to being a void-returning async method, and the Action passed into the Time method will be for that void method.&amp;#160; Thus, when Time invokes the Action, the Action will return as soon as it hits the first await that yields, which is our await for the delay task.&amp;#160; This means that we’re really only timing the invocation of the async method up until the await, but not including the time to await the task or what comes after it.&lt;/p&gt;  &lt;p&gt;We can fix this by modifying our Time function to accept a Func&amp;lt;Task&amp;gt; instead of an Action:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public static double&lt;/font&gt; Time(&lt;font color="#4bacc6"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#4bacc6"&gt;Task&lt;/font&gt;&amp;gt; func, &lt;font color="#0000ff"&gt;int&lt;/font&gt; iters=10)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; sw = &lt;font color="#4bacc6"&gt;Stopwatch&lt;/font&gt;.StartNew();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;for&lt;/font&gt; (&lt;font color="#0000ff"&gt;int&lt;/font&gt; i = 0; i &amp;lt; iters; i++) func().Wait();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; sw.Elapsed.TotalSeconds / iters;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now when I compile and run our async lambda, I get the following output that’s what I’d expect:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;Seconds: 1.0078671       &lt;br /&gt;Press any key to continue . . .&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Void-returning methods aren’t the only potentially problematic area; they’re just the easiest example to highlight, because it’s very clear from the signature that they don’t return anything and thus are only useful for their side-effects, which means that code invoking them typically needs them to run to completion before making forward progress (since it likely depends on those side-effects having taken place), and async void methods defy that.&lt;/p&gt;  &lt;p&gt;A more complicated but still problematic example is a generic method that accepts an Action as a parameter and returns a Task, or that accepts a Func&amp;lt;…,TResult&amp;gt; as a parameter and returns a Task&amp;lt;TResult&amp;gt;, such as Task.Factory.StartNew.&amp;#160; Consider the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; t = &lt;font color="#4bacc6"&gt;Task&lt;/font&gt;.Factory.StartNew(() =&amp;gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Thread&lt;/font&gt;.Sleep(1000);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; 42;        &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Here StartNew accepts a delegate of type Func&amp;lt;int&amp;gt;, and returns a Task&amp;lt;int&amp;gt; representing the execution of the Func&amp;lt;int&amp;gt; delegate.&amp;#160; Makes sense.&amp;#160; But now consider the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; t = &lt;font color="#4bacc6"&gt;Task&lt;/font&gt;.Factory.StartNew(&lt;font color="#0000ff"&gt;async&lt;/font&gt; () =&amp;gt;        &lt;br /&gt;{        &lt;br /&gt;&lt;font color="#4bacc6"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;await &lt;/font&gt;Task&lt;/font&gt;.Delay(1000);        &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; return&lt;/font&gt; 42;        &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Any guesses as to what the type of ‘t’ is?&amp;#160; StartNew accepts a Func&amp;lt;TResult&amp;gt; and returns a Task&amp;lt;TResult&amp;gt;.&amp;#160; We’re passing in an async lambda that will give back a Task&amp;lt;int&amp;gt;, which means the TResult in Func&amp;lt;TResult&amp;gt; is actually Task&amp;lt;int&amp;gt;, such that the delegate provided to StartNew is a Func&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;.&amp;#160; That means that this call to StartNew is actually returning a Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;.&amp;#160; The task created by StartNew will invoke the Func&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;, which will run synchronously until the first await that yields, at which point the Func&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt; will return, handing back the result Task&amp;lt;int&amp;gt; that represents the async lambda’s execution.&amp;#160; StartNew will then complete the Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt; that it handed back, since the delegate associated with that task has completed its synchronous execution.&amp;#160; If I wrote code that depended on the returned task’s completion to mean that the async lambda had completed, I’d be sorely disappointed.&amp;#160; It’s actually the returned task’s Result (which is itself a Task&amp;lt;int&amp;gt;) that represents the async lambda.&lt;/p&gt;  &lt;p&gt;There are a few ways to address this, such as using the Unwrap method:&amp;#160; &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; t = &lt;font color="#4bacc6"&gt;Task&lt;/font&gt;.Factory.StartNew(&lt;font color="#0000ff"&gt;async&lt;/font&gt; () =&amp;gt;        &lt;br /&gt;{        &lt;br /&gt;&lt;font color="#4bacc6"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; await &lt;/font&gt;Task&lt;/font&gt;.Delay(1000);        &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; return&lt;/font&gt; 42;        &lt;br /&gt;})&lt;strong&gt;.Unwrap()&lt;/strong&gt;;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For more information, see my previous blog post on this (and on how Task.Run differs in behavior here from Task.Factory.StartNew) at &lt;a title="http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx" href="http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx"&gt;http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10265476" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>When “ExecuteSynchronously” doesn’t execute synchronously</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/07/10265067.aspx</link><pubDate>Tue, 07 Feb 2012 19:22:47 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10265067</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10265067</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10265067</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/07/10265067.aspx#comments</comments><description>&lt;p&gt;When creating a task continuation with ContinueWith, developers have the opportunity to provide a TaskContinuationOptions enum value, which could include the TaskContinuationOptions.ExecuteSynchronously flag.&amp;#160; ExecuteSynchronously is a request for an optimization to run the continuation task on the same thread that completed the antecedent task off of which we continued, in effect running the continuation as part of the antecedent’s transition to a final state (the default behavior for ContinueWith if this flag isn’t specified is to run the continuation asynchronously, meaning that when the antecedent task completes, the continuation task will be queued rather than executed).&amp;#160; I explicitly used the word “request” in the previous sentence, because while TPL strives to honor this as much as possible, there are in fact a few cases where continuations created with TaskContinuationOptions.ExecuteSynchronously will still run asynchronously.&amp;#160; (What follows is a discussion of TPL’s current implementation in .NET 4 and the .NET 4.5 Developer Preview.)&lt;/p&gt;  &lt;p&gt;One condition that will force a continuation to run asynchronously is if there is a thread abort pending on the thread completing the antecedent task.&amp;#160; It could be dangerous for TPL to continue running arbitrary amounts of work on a thread that the CLR is trying to tear down, so when a task completes and a thread abort is pending, all ContinueWith continuations will be queued rather than executed.&amp;#160; Here’s a code sample to demonstrate this behavior:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;using System;       &lt;br /&gt;using System.Threading;        &lt;br /&gt;using System.Threading.Tasks;        &lt;br /&gt;        &lt;br /&gt;class Program        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; static void Main()        &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; var tcs = new TaskCompletionSource&amp;lt;bool&amp;gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var cont = tcs.Task.ContinueWith(delegate&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(Thread.CurrentThread.ManagedThreadId);&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }, TaskContinuationOptions.ExecuteSynchronously);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new Thread(() =&amp;gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(Thread.CurrentThread.ManagedThreadId);&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; try        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Thread.CurrentThread.Abort();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; finally        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; tcs.SetResult(true);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }).Start();        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; cont.Wait();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;If you try running this code, you’ll find that it outputs two different thread IDs, one for the thread that’s completing the antecedent task and one for the thread that’s running the continuation.&amp;#160; If you then comment out the line that’s issuing the Abort, you’ll find that it’ll output the same ID twice, since the continuation is then running synchronously on the same thread that completed the antecedent task.&lt;/p&gt;  &lt;p&gt;Another condition that may force a continuation to run asynchronously has to do with stack overflows.&amp;#160; TPL has logic used in a few places (e.g. Wait inlining, ExecuteSynchronously) to determine whether it’s too deep on the stack to safely execute.&amp;#160; If TPL detects that it’s too close to the thread’s guard page for comfort, such that running the continuation synchronously has a high risk of overflowing, then TPL will force the continuation to run asynchronously.&amp;#160; We can see this behavior with the following code example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;using System;       &lt;br /&gt;using System.Collections.Generic;        &lt;br /&gt;using System.Linq;        &lt;br /&gt;using System.Threading;        &lt;br /&gt;using System.Threading.Tasks;        &lt;br /&gt;        &lt;br /&gt;class Program        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; static void Main()        &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; var tcs = new TaskCompletionSource&amp;lt;bool&amp;gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var t = (Task)tcs.Task;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var counts = new List&amp;lt;int&amp;gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; int lastThreadId = Thread.CurrentThread.ManagedThreadId;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; int curCount = 0;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; for (int i = 0; i &amp;lt; 1000000; i++)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; t = t.ContinueWith(delegate        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; int threadId = Thread.CurrentThread.ManagedThreadId;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (threadId == lastThreadId)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; curCount++;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; else        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; lastThreadId = threadId;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; counts.Add(curCount);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; curCount = 0;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }, TaskContinuationOptions.ExecuteSynchronously);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; tcs.SetResult(true);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; t.Wait();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine((int)counts.Average());        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Here, we’re creating a chain of a million ExecuteSynchronously continuations.&amp;#160; With a default stack size of 1MB, and with multiple stack frames require per continuation execution, this program would certainly overflow the stack if TPL didn’t account for it.&amp;#160; However, if we run this, we should see that it successfully executes without crashing.&amp;#160; Note that this code is keeping track of how many continuations contiguously run on the same thread so that we can see approximately how many continuations end up running synchronously before one is forced to run asynchronously in order to avoid an overflow (this isn’t a 100% accurate measure, as it’s theoretically possible the continuation could be queued to run asynchronously but then end up running on the same thread, if the thread unwound the whole stack and then picked up the continuation task to run it before any other thread did, but for our purposes it’s good enough).&amp;#160; When I run this, I see that on average we run approximately 2200 continuations synchronously before we force one to run asynchronously.&lt;/p&gt;  &lt;p&gt;The third current condition where ExecuteSynchronously continuations won’t run synchronously is when the target scheduler doesn’t allow it.&amp;#160; A TaskScheduler has the ability to say whether tasks are able to run on the current thread or not.&amp;#160; For example, if you created a custom StaTaskScheduler whose job was to run tasks on STA threads, it shouldn’t allow a task to run on an MTA thread, so that scheduler should be able to override the ExecuteSynchronously behavior in the case where the antecedent isn’t completing on an STA thread.&amp;#160; When TPL goes to run a synchronous continuation, it does so via the target TaskScheduler’s TryExecuteTaskInline method.&amp;#160; The scheduler can either choose to execute the task in that call, or it can choose to return false, meaning that it refused to run the task, and in the latter case, TPL will then queue the continuation to the scheduler to run asynchronously.&amp;#160; Here’s an example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;using System;       &lt;br /&gt;using System.Collections.Generic;        &lt;br /&gt;using System.Threading;        &lt;br /&gt;using System.Threading.Tasks;        &lt;br /&gt;        &lt;br /&gt;class Program        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; static void Main()        &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; Console.WriteLine(Thread.CurrentThread.ManagedThreadId);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var tcs = new TaskCompletionSource&amp;lt;bool&amp;gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var cont = tcs.Task.ContinueWith(delegate        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(Thread.CurrentThread.ManagedThreadId);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, new DummyTaskScheduler());        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; tcs.SetResult(true);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; cont.Wait();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;class DummyTaskScheduler : TaskScheduler        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; protected override void QueueTask(Task task)        &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; ThreadPool.QueueUserWorkItem(delegate { TryExecuteTask(task); });        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)        &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; //return TryExecuteTask(task);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return false;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; protected override IEnumerable&amp;lt;Task&amp;gt; GetScheduledTasks()        &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; return null;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Note that our dummy TaskScheduler’s TryExecuteTaskInline is returning false and not executing the task; thus, even though the continuation has ExecuteSynchronously specified, the continuation will still run asynchronously.&amp;#160; As with the previous examples, you can see this by running the code, which will output two different thread IDs.&amp;#160; If you then modify TryExecuteTaskInline by commenting out the existing “return false;” and uncommenting in the “return TryExecuteTask(task);” line, then the program should output the same thread ID twice.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10265067" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>FromAsync(asyncResult, …) vs FromAsync(beginMethod, …)</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/06/10264610.aspx</link><pubDate>Mon, 06 Feb 2012 21:25:52 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10264610</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10264610</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10264610</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/06/10264610.aspx#comments</comments><description>&lt;p&gt;The Task Parallel Library (TPL) provides a set of “&lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/09/9716439.aspx"&gt;FromAsync&lt;/a&gt;” helper methods that create a Task or a Task&amp;lt;TResult&amp;gt; to represent an invocation of an APM method pair, i.e. BeginXx / EndXx.&amp;#160; There are, however, &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx"&gt;two different flavors&lt;/a&gt; among these overloads: ones that accept an IAsyncResult “asyncResult” as the first parameter, and ones that accept a Func&amp;lt;…,AsyncCallback,object,IAsyncResult&amp;gt; “beginMethod” as the first parameter.&amp;#160; What’s the difference, and why would you choose one over the other?&lt;/p&gt;  &lt;p&gt;The fundamental difference between the two is in how the endMethod delegate is invoked.&amp;#160; When FromAsync is given a beginMethod delegate, it passes to that beginMethod an AsyncCallback that will invoke the endMethod.&amp;#160; As with any APM implemention, it’s up to the BeginXx’s implementation to eventually invoke this AsyncCallback when the async operation has completed.&amp;#160; In contrast, the IAsyncResult interface doesn’t provide any mechanism via which to provide a callback that will be invoked when the operation represented by the IAsyncResult is completed, so when FromAsync is handed an IAsyncResult, it needs to monitor the IAsyncResult’s WaitHandle.&lt;/p&gt;  &lt;p&gt;Monitoring the IAsyncResult’s WaitHandle (as returned from its AsyncWaitHandle property) has a few implications.&amp;#160; First, since the APM pattern is all about asynchrony, most IAsyncResult implementations strive to avoid allocating the WaitHandle, only doing so lazily if it’s actually requested.&amp;#160; Thus, by accessing the IAsyncResult’s AsyncWaitHandle property, FromAsync is likely forcing allocation of a WaitHandle (and the associated operating system primitives) that otherwise wouldn’t need to be allocated.&amp;#160; Second, the only way to “monitor” a WaitHandle to know when it’s been set is to wait on it, which is a potentially blocking operation.&amp;#160; Obviously, FromAsync isn’t going to block the current thread by waiting on this handle (that wouldn’t be very async of it), so instead it relies on the ThreadPool.&amp;#160; It could queue a work item to block on the handle, but that would end up burning a ThreadPool thread for each such call.&amp;#160; Instead, FromAsync relies on &lt;a href="http://msdn.microsoft.com/en-us/library/hka8cs9z.aspx"&gt;ThreadPool.RegisterWaitForSingleObject&lt;/a&gt;, a function that is specifically geared towards using the ThreadPool to more efficiently wait for handles. According to the MSDN documentation, it does so by waiting on multiple handles from a single thread via WaitForMultipleObjects; however, there are a limit to how many handles it can wait on from each thread, so while this will end up burning fewer threads than if we blocked one thread per handle, it’s still far from ideal.&lt;/p&gt;  &lt;p&gt;As such, if you have a choice between using FromAsync(asyncResult, …) and using FromAsync(beginMethod, …), pick the latter that uses a delegate instead of an IAsyncResult.&amp;#160; When might you choose to use the former?&amp;#160; The IAsyncResult overloads can still be useful in a few cases.&amp;#160; For example, there are some BeginXx methods with signatures that don’t exactly conform to the beginMethod functions accepted by the built-in FromAsync overloads, e.g. they have more parameters than the built-in versions can handle.&amp;#160; In such a case, you could choose to either write your own FromAsync method to accommodate the custom signature, or you could use an IAsyncResult overload, since it doesn’t care about the shape of the BeginXx method, only about its result.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10264610" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Building a custom GetOrAdd method for ConcurrentDictionary&lt;TKey,TValue&gt;</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/04/10264111.aspx</link><pubDate>Sun, 05 Feb 2012 04:14:37 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10264111</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10264111</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10264111</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/04/10264111.aspx#comments</comments><description>&lt;p&gt;I was recently asked by a developer about getting some additional information out of ConcurrentDictionary&amp;lt;TKey,TValue&amp;gt;’s GetOrAdd method.&amp;#160; &lt;/p&gt;  &lt;p&gt;As a reminder, GetOrAdd either returns the value for a key currently in the dictionary, or if that key doesn’t have a value, it adds a value for the key as dictated by either a TValue provided by the caller or by executing a Func&amp;lt;TKey,TValue&amp;gt; provided by the caller.&amp;#160; It then returns the new value.&amp;#160; However, it doesn’t tell the caller which happened; all the caller knows is that it’s handed back the value (existing or new) that was associated with the key.&amp;#160; The developer wanted to know which occurred, as he needed to notify some other code that a new value had been added.&lt;/p&gt;  &lt;p&gt;While the built-in GetOrAdd method doesn’t provide this, we can build our own GetOrAdd overload to provide this behavior, building it on top of the existing TryGetValue and TryAdd methods:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public static&lt;/font&gt; TValue GetOrAdd&amp;lt;TKey, TValue&amp;gt;(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#4bacc6"&gt;ConcurrentDictionary&lt;/font&gt;&amp;lt;TKey, TValue&amp;gt; dict,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;TKey key, &lt;font color="#4bacc6"&gt;Func&lt;/font&gt;&amp;lt;TKey, TValue&amp;gt; generator,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;out bool&lt;/font&gt; added)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; TValue value;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while&lt;/font&gt; (&lt;font color="#0000ff"&gt;true&lt;/font&gt;)        &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; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (dict.TryGetValue(key, &lt;font color="#0000ff"&gt;out&lt;/font&gt; value))&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; added = &lt;font color="#0000ff"&gt;false&lt;/font&gt;;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; value;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; value = generator(key);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (dict.TryAdd(key, value))&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; added = &lt;font color="#0000ff"&gt;true&lt;/font&gt;;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; value;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The approach here is straightforward.&amp;#160; We try to get the key’s value in the dictionary.&amp;#160; If we can, then we use an out parameter to indicate that a new value was not added and we return the value we retrieved.&amp;#160; If we can’t, then we try to add a new value as generated by the provided Func&amp;lt;TKey,TValue&amp;gt;; assuming that succeeds, we note the addition via the out parameter and we return the newly added value.&amp;#160; If the addition fails (which should only happen if another thread concurrently added an item since we called TryGetValue), then we loop around and try the whole process again.&lt;/p&gt;  &lt;p&gt;Using the TryGetValue, TryAdd, and TryUpdate on ConcurrentDictionary&amp;lt;TKey,TValue&amp;gt;, it’s possible to build many variations of this kind of behavior.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10264111" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Coordination+Data+Structures/">Coordination Data Structures</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Know Thine Implicit Allocations</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/03/10263921.aspx</link><pubDate>Sat, 04 Feb 2012 01:26:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10263921</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10263921</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10263921</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/03/10263921.aspx#comments</comments><description>&lt;p&gt;For .NET 4.5, we’ve invested quite a bit of effort into performance, and in particular for the Task Parallel Library (Joe Hoag wrote a &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235962.aspx"&gt;good paper&lt;/a&gt; covering some of these improvements).&amp;#160; We focused such effort on TPL because it is a core component used in async programming and at a foundational level for many libraries and applications.&amp;#160; Small tweaks to the performance characteristics of TPL can thusly have a noticeable impact on the performance of these higher-level systems.&lt;/p&gt;  &lt;p&gt;In particular, one of the areas we focused a lot of attention on is memory utilization: how many objects are we allocating, and how big are those objects.&amp;#160; This is primarily due to the subsequent costs of garbage collection necessary to clean up those objects… the less we allocate, the less often the GC will need to run and the shorter it will take to run.&amp;#160; Sometimes these allocations are clearly visible, in that you see a “new” expression in the code.&amp;#160; But often these allocations are hidden.&lt;/p&gt;  &lt;p&gt;The Task Parallel Library is written in C#, and C# has some incredibly useful features that help to make programming very productive.&amp;#160; The implementation of those features, however, can sometimes result in allocations of which it’s easy to be blissfully unaware. The developers that wrote the C# compiler have done some great work to make the code generated by the compiler efficient, and they’ve implemented a variety of optimizations to help minimize allocations.&amp;#160; Still, if you care about eking out the best performance possible and minimizing all possible allocations in the process, it can be very useful to understand the intricacies of the code the compiler generates such that you can bend the behavior better to your will.&lt;/p&gt;  &lt;p&gt;In this post, I’ll highlight some of these behaviors we came across during our performance push for TPL, and I’ll demonstrate how you can work around them to help get the best performance possible.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;WARNING: Everything I’m discussing in this post is an implementation detail based on one version of the C# compiler (that in .NET 4.5 Developer Preview).&amp;#160; It’s certainly possible that these characteristics may change in a future release, as the C# compiler gets more and more optimizations added to it.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Closure and Delegate Allocations&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Lambdas and anonymous methods are very powerful features that save the developer from having to write a lot of boilerplate code.&amp;#160; Consider the Framework’s ThreadPool.QueueUserWorkItem method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static bool ThreadPool(WaitCallback callback);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With lambdas/anonymous methods, I can write code like the following (I’m not recommending this as an approach towards writing to a stream asynchronously, rather just using it as an example of passing state around):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte [] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(delegate        &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; stream.Write(data, 0, data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Before lambdas/anonymous methods were introduced, C# developers wanting to call a method that accepted a delegate would typically need to define a class to store their state, add a method to that class to do their processing, and then create a delegate that pointed to that method on that state instance, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte [] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var state = new WriteOnPoolState();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state.stream = stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state.data = data;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(new WaitCallback(state.Invoke));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private sealed class WriteOnPoolState        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public Stream stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public byte [] data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void Invoke(object ignored)        &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; stream.Write(data, 0, data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now in C#, when you use an anonymous method or lambda, the compiler actually ends up generating code almost identical to this on your behalf so that you no longer have to do so manually.&amp;#160; Here’s a decompiled version of what gets generated for my previous example that used an anonymous method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var locals2 = new DisplayClass1();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; locals2.stream = stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; locals2.data = data;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(locals2.&amp;lt;WriteOnPool&amp;gt;b__0));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;[CompilerGenerated]        &lt;br /&gt;private sealed class DisplayClass1        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public Stream stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public byte[] data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void &amp;lt;WriteOnPool&amp;gt;b__0(object param0)        &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; this.stream.Write(this.data, 0, this.data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The important thing to note here is that there are two allocations involved: one for the closure object (in my hand-written version, WriteOnPoolState, and in the compiler-generated version, DisplayClass1), and one for the delegate to the method on the closure.&amp;#160; For a method that simply accepts a delegate, there’s really no way around two allocations: the delegate object needs to be allocated, and it needs to target an object containing the state (assuming that state needs to change for each invocation, this state object also needs to be allocated for each call).&lt;/p&gt;  &lt;p&gt;Luckily, many library methods that accept delegates recognize the need to pass state into the method, and thus accept not only a delegate object but also a state object that will be passed into the delegate when it’s invoked.&amp;#160; In fact, ThreadPool has an additional overload of QueueUserWorkItem that accepts both, and the overload we’ve been using above just passes in null; that’s why the WriteOnPoolState.Invoke and DisplayClass1.&amp;lt;WriteOnPool&amp;gt;b__0 methods both accept an object parameter, so as to match the required signature of a WaitCallback, which accepts an object parameter.&lt;/p&gt;  &lt;p&gt;This pattern of accepting an object state is useful because it allows us to avoid allocations.&amp;#160; The reason we need to allocate a delegate each time is because its Target needs to point to the right “this” object.&amp;#160; But if there is no “this”, i.e. we’re dealing with a static method, then we can reuse the same delegate object over and over, simply passing in different state as a parameter each time.&amp;#160; To achieve that, we can rewrite our WriteOnPool example as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte [] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var state = new WriteOnPoolState();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state.stream = stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state.data = data;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(s_writeOnPoolBody, state);        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private static readonly WaitCallback s_writeOnPoolBody =&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(WriteOnPoolBody);        &lt;br /&gt;        &lt;br /&gt;private static void WriteOnPoolBody(object state)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var poolState = (WriteOnPoolState)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; poolState.stream.Write(poolState.data, 0, poolState.data.Length);        &lt;br /&gt;}&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;        &lt;br /&gt;private sealed class WriteOnPoolState        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public Stream stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public byte [] data;         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We’re now still allocating a delegate and a state object, but we allocate the delegate only once and cache it into a static field.&amp;#160; On each call to WriteOnPool, then, we only allocate once, for the WriteOnPoolState object, saving half of the allocations.&lt;/p&gt;  &lt;p&gt;As it turns out, the C# compiler has smarts to provide similar savings when using lambdas and anonymous methods.&amp;#160; Let’s say I instead rewrite my implementation as follows, still using a lambda, but now passing in my state via the object state parameter and ensuring that my lambda doesn’t close over anything (I’m also using a Tuple&amp;lt;,&amp;gt; for conciseness to avoid needing to define my own custom state type):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(state =&amp;gt;        &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; var poolState = (Tuple&amp;lt;Stream,byte[]&amp;gt;)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item1.Write(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item2, 0, poolState.Item2.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }, Tuple.Create(stream, data));        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This now results in the following code from the compiler:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (CachedAnonymousMethodDelegate1 == null)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CachedAnonymousMethodDelegate1 =&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(Program.&amp;lt;WriteOnPool&amp;gt;b__0);        &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CachedAnonymousMethodDelegate1,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Tuple.Create&amp;lt;Stream, byte[]&amp;gt;(stream, data));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;[CompilerGenerated]        &lt;br /&gt;private static WaitCallback CachedAnonymousMethodDelegate1;        &lt;br /&gt;        &lt;br /&gt;[CompilerGenerated]        &lt;br /&gt;private static void &amp;lt;WriteOnPool&amp;gt;b__0(object state)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Tuple&amp;lt;Stream, byte[]&amp;gt; poolState = (Tuple&amp;lt;Stream, byte[]&amp;gt;) state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; poolState.Item1.Write(poolState.Item2, 0, poolState.Item2.Length);        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Note that the compiler has done something very similar to what we did manually, creating a static field to cache the delegate.&amp;#160; The primary difference between what we manually wrote and what the compiler generated is the compiler is lazily instantiating the delegate on first use, rather than doing it in the static constructor as we did by using a field initializer.&amp;#160; So, we get to have our cake and eat most of it, too… we still get most of the convenience of lambdas while getting the efficiency benefits of the delegate caching.&amp;#160; And, of course, if the state I’m trying to pass in is already a single object, that object can be passed in directly (rather than wrapping it in a state object), bringing us down to zero additional allocations.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;When Automatic Caching Fails&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This is all well and good, but it can lead us into a fall sense of security, as there are times when the compiler will not cache the delegate.&lt;/p&gt;  &lt;p&gt;One prime example is that the compiler won’t cache the delegate when a method group is used rather than a lambda / anonymous method, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; WriteOnPoolCallback,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Tuple.Create(stream, data));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private static void WriteOnPoolCallback(object state)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var poolState = (Tuple&amp;lt;Stream, byte[]&amp;gt;)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; poolState.Item1.Write(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item2, 0, poolState.Item2.Length);        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Some developers prefer the explicitness of having a named method, but the compiler currently generates code like the following for this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(Program.WriteOnPoolCallback),&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Tuple.Create&amp;lt;Stream, byte[]&amp;gt;(stream, data));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private static void WriteOnPoolCallback(object state)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Tuple&amp;lt;Stream, byte[]&amp;gt; poolState = (Tuple&amp;lt;Stream, byte[]&amp;gt;) state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; poolState.Item1.Write(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item2, 0, poolState.Item2.Length);        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the delegate allocation on each call.&amp;#160; In such a situation, you might prefer to do the caching manually, or to revert to using a lambda or anonymous method.&lt;/p&gt;  &lt;p&gt;Another example where the compiler won’t cache is when dealing with certain patterns of generics usage.&amp;#160; Consider the following variation.&amp;#160; Here rather than writing a byte[] to the stream, I’m using a BinaryFormatter to serialize an arbitrary generic T to the stream:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public void WriteOnPool&amp;lt;T&amp;gt;(Stream stream, T data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(state =&amp;gt;        &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; var poolState = (Tuple&amp;lt;Stream, T&amp;gt;)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new BinaryFormatter().Serialize(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item1, poolState.Item2);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }, Tuple.Create(stream, data));        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The compiler will currently not cache a delegate for this case, instead generating code like the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public void WriteOnPool&amp;lt;T&amp;gt;(Stream stream, T data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(Program.&amp;lt;WriteOnPool&amp;gt;b__0&amp;lt;T&amp;gt;),&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Tuple.Create&amp;lt;Stream, T&amp;gt;(stream, data));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;[CompilerGenerated]        &lt;br /&gt;private static void &amp;lt;WriteOnPool&amp;gt;b__0&amp;lt;T&amp;gt;(object state)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Tuple&amp;lt;Stream, T&amp;gt; poolState = (Tuple&amp;lt;Stream, T&amp;gt;) state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; new BinaryFormatter().Serialize(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item1, poolState.Item2);        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A little thought reveals why the compiler doesn’t use the same caching pattern it does elsewhere.&amp;#160; Notice that the method generated for the lambda is a generic method, and for it to be cached, it would need to be cached in a static field for each T that might exist… that’s not possible in a field on a class that’s not parameterized on the same generic type parameter.&amp;#160; We can manually work around this by caching the delegate manually: we just need to create a generic type to contain the field:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public void WriteOnPool&amp;lt;T&amp;gt;(Stream stream, T data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; DelegateCache&amp;lt;T&amp;gt;.s_writeOnPoolCallback,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Tuple.Create(stream, data));        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private static class DelegateCache&amp;lt;T&amp;gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; internal static readonly WaitCallback s_writeOnPoolCallback =         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; state =&amp;gt;        &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; var poolState = (Tuple&amp;lt;Stream, T&amp;gt;)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new BinaryFormatter().Serialize(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; poolState.Item1, poolState.Item2);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Theoretically, the compiler could perform a similar transformation, for example creating one such generic cache per assembly and per generic arity, but it currently does not do so.&lt;/p&gt;  &lt;p&gt;Another common case where such lack-of-caching goes unnoticed is when dealing with instance methods and data.&amp;#160; Consider the following similar code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;internal class MyCoolType       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private Stream m_stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private byte[] m_data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void WriteOnPool()        &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; ThreadPool.QueueUserWorkItem(delegate        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; m_stream.Write(m_data, 0, m_data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; });        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This example will generate code like the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;internal class MyCoolType       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private Stream m_stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private byte[] m_data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void WriteOnPool()        &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; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(this.&amp;lt;WriteOnPool&amp;gt;b__0));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [CompilerGenerated]        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private void &amp;lt;WriteOnPool&amp;gt;b__0(object param0)        &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; this.m_stream.Write(this.m_data, 0, this.m_data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The anonymous method refers implicitly to ‘this’, closing over member fields of the current instance.&amp;#160; As such, the compiler generates an instance method for that anonymous method, and then because it needs a delegate instance with a Target set to this particular instance, each call to WriteOnPool will end up allocating a new delegate (it would be possible for the compiler to have added an instance field in order to cache this delegate, but that could have negative consequences, such as making each instance of this class bigger, and the compiler can’t easily reason about the global impacts of such caching).&amp;#160; Of course, we have knowledge that the compiler doesn’t have: we know that we can use the object state parameter in order to pass data into the method.&amp;#160; So, we could instead write our code as:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;internal class MyCoolType       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private Stream m_stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private byte[] m_data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void WriteOnPool()        &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; ThreadPool.QueueUserWorkItem(state =&amp;gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; MyCoolType mct = (MyCoolType)state;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; mct.m_stream.Write(mct.m_data, 0, mct.m_data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }, this);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;or as:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;internal class MyCoolType       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private Stream m_stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private byte[] m_data;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void WriteOnPool()        &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; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; state =&amp;gt; ((MyCoolType)state).Write(), this);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private void Write()        &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; m_stream.Write(m_data, 0, m_data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;and in both cases, we’ll get the caching we expect.&amp;#160; This is an example of the case I referred to earlier, where we already have a single state object to pass in, and thus we don’t need to allocate a wrapper (e.g. a tuple), which means there are no additional allocations here.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Closures and Fast Paths&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;There are other times when the compiler isn’t yet quite as clever as we might expect it to be.&amp;#160; One case in which this comes up is when using “fast paths” to optimize frequented code paths.&amp;#160; Consider a change to our WriteOnPool method: the goal of the method isn’t to queue a work item to do the write, but rather to ensure the write happens on a ThreadPool thread; as such, if we’re already on a ThreadPool thread, we can avoid the queueing operation:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (Thread.CurrentThread.IsThreadPoolThread)        &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; stream.Write(data, 0, data.Length);        &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;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(delegate        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; stream.Write(data, 0, data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; });        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I might then expect that my “fast path” that occurs when I’m already on a ThreadPool thread won’t involve any additional allocations for the closure/delegate used on the “slow path.”&amp;#160; But such an expectation is based on an assumption that the compiler allocates the closure in the “else” block.&amp;#160; In fact, the compiler currently generates code like the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; var locals3 = new DisplayClass2();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; locals3.stream = stream;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; locals3.data = data;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (Thread.CurrentThread.IsThreadPoolThread)        &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; locals3.stream.Write(locals3.data, 0, locals3.data.Length);        &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;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new WaitCallback(locals3.&amp;lt;WriteOnPool&amp;gt;b__0));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;[CompilerGenerated]        &lt;br /&gt;private sealed class DisplayClass2        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public byte[] data;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public Stream stream;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public void &amp;lt;WriteOnPool&amp;gt;b__0(object param0)        &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; this.stream.Write(this.data, 0, this.data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Note that the “locals” that are captured into the closure actually live on the heap-allocated closure object and are accessed there, even from code paths that don’t use the closure. Thus, the closure object gets allocated at the beginning of the method.&amp;#160; This means that we’re still paying for the closure object even if we only take the “fast path” that doesn’t actually require it.&amp;#160; If we instead separate out the closure into a separate method, we can eliminate that allocation from the fast path, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static void WriteOnPool(Stream stream, byte[] data)       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (Thread.CurrentThread.IsThreadPoolThread)        &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; stream.Write(data, 0, data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; else WriteOnPoolPrivate(stream, data);        &lt;br /&gt;}        &lt;br /&gt;        &lt;br /&gt;private static void WriteOnPoolPrivate(Stream stream, byte[] data)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ThreadPool.QueueUserWorkItem(delegate        &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; stream.Write(data, 0, data.Length);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;strong&gt;Moral of the Story&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;C# and Visual Basic provide some very powerful language features for you to use, and they typically do a very good job of implementing what’s under the hood.&amp;#160; But if your particular scenario demands pedal-to-the-medal performance, you need to at least understand what’s happening on your behalf so that you can better influence it as necessary.&amp;#160; Get friendly with tools like .NET Reflector that help you to see what’s actually going on in the compiled code. &lt;/p&gt;  &lt;p&gt;If you do use a decompiler for this kind of analysis, be certain that it’s not sweeping such details under the rug for you.&amp;#160; A primary use of these decompilers is to get high-quality source generated from low-level IL, and thus decompilers will often attempt to decompile back to source that employs anonymous methods and lambdas and the like.&amp;#160; If instead your goal is to get a closer view on what’s actually happening, try tweaking the settings of the decompiler to minimize what language features it reverse engineers to, e.g. in .NET Reflector, you can change the “optimization level” so that it shows you code like what I’ve shown in this post, rather than hiding these allocations behind a lambda.&lt;/p&gt;  &lt;p&gt;One last thought. Throughout this post, I kept harping on the number of allocations, but I didn’t spend much time on the size of the allocations. The number of allocations is only one aspect to consider. We also want to consider the amount of memory being allocated, as that will factor into how often the garbage collector runs. There are lots of tools to help determine the amount of memory .NET applications are allocating, but when prototyping I often find myself using a function like the following to give me a rough sense for what something is costing:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;public static class MemoryAnalysis       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public static long AveragedApproximateSize&amp;lt;T&amp;gt;(Func&amp;lt;T&amp;gt; rootGenerator) where T : class        &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; const int iters = 1000000;        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var items = new object[iters];        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; long start = GC.GetTotalMemory(true);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; for (int i = 0; i &amp;lt; items.Length; i++)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; items[i] = rootGenerator();        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; long end = GC.GetTotalMemory(true);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; GC.KeepAlive(items);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return (long)Math.Round((end - start) / (double)iters);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When I then run:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;static void Main()       &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(MemoryAnalysis.AveragedApproximateSize(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; () =&amp;gt; new WriteOnPoolState()));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(MemoryAnalysis.AveragedApproximateSize(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; () =&amp;gt; new WaitCallback(WriteOnPoolBody)));        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I see that WriteOnPoolState is 16 bytes and WaitCallback is 32 bytes (in a 32-bit compilation), which makes logical sense if you add up the size of the fields on the objects plus the object headers. That means that for the examples where we were able to eliminate the delegate allocation by caching the delegate in a static, we were not only saving half the number of allocations, but we were also saving 2/3&lt;sup&gt;rds&lt;/sup&gt; of the memory being allocated.&lt;/p&gt;  &lt;p&gt;Happy optimizing.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10263921" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Await, SynchronizationContext, and Console Apps: Part 3</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/02/02/10263555.aspx</link><pubDate>Fri, 03 Feb 2012 06:46:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10263555</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10263555</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10263555</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/02/02/10263555.aspx#comments</comments><description>&lt;p&gt;In &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx"&gt;Part 1&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx"&gt;Part 2&lt;/a&gt; of this short series, I demonstrated how you can build a SynchronizationContext and use it run an async method such that all of the continuations in that method will run on serialized on the current thread.&amp;nbsp; This can be helpful when executing async methods in a console app, or in a unit test framework that doesn&amp;rsquo;t directly support async methods.&amp;nbsp; However, the support I showed thus far targets async methods that return Task&amp;hellip; what about async methods that return void?&lt;/p&gt;
&lt;p&gt;C# and Visual Basic support two flavors of async methods: ones that return tasks (either Task or Task&amp;lt;T&amp;gt;) and ones that return void.&amp;nbsp; The former use the returned Task to represent the completion of the async method. In the case of an &amp;ldquo;async void&amp;rdquo; method, however, there is no returned Task to represent the method&amp;rsquo;s processing.&amp;nbsp; Instead, &amp;ldquo;async void&amp;rdquo; methods interact with the current SynchronizationContext to alert the context to the async method&amp;rsquo;s execution status.&amp;nbsp; Before entering the body of the async method, if there is a current SynchronizationContext, it is retrieved and its OperationStarted method is called.&amp;nbsp; And after the async method has completed, that same context has its OperationCompleted method called.&amp;nbsp; Further, if an exception goes unhandled in the body of the async void method, the throwing of that exception is Post to the SynchronizationContext, so that the exception escapes back to the context for it to handle as it pleases.&lt;/p&gt;
&lt;p&gt;All of this means that if we want our AsyncPump to be able to handle &amp;ldquo;async void&amp;rdquo; methods in addition to &amp;ldquo;async Task&amp;rdquo; methods, we need to augment the type slightly.&amp;nbsp; First, we need to augment our SingleThreadSynchronizationContext to react appropriate to calls to OperationStarted and OperationCompleted.&amp;nbsp; These methods need to maintain a count of how many outstanding operations there are, such that when the count reaches 0, we call Complete, just as &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx"&gt;before&lt;/a&gt; we called Complete when the async method&amp;rsquo;s Task completed.&amp;nbsp; We do this by adding three members to the custom context:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;span style="color: #333333;" color="#333333"&gt; m_&lt;/span&gt;operationCount = 0;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public override void&lt;/span&gt; OperationStarted() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Interlocked&lt;/span&gt;.Increment(&lt;span style="color: #0000ff;" color="#0000ff"&gt;ref&lt;/span&gt; m_operationCount); &lt;br /&gt;} &lt;br /&gt; &lt;br /&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public override void&lt;/span&gt; OperationCompleted() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;if&lt;/span&gt; (&lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Interlocked&lt;/span&gt;.Decrement(&lt;span style="color: #0000ff;" color="#0000ff"&gt;ref&lt;/span&gt; m_operationCount) == 0) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Complete(); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Then we need to add a new AsyncPump.Run overload that works with Action (for &amp;ldquo;async void&amp;rdquo; methods) instead of with Func&amp;lt;Task&amp;gt; (for &amp;ldquo;async Task&amp;rdquo; methods). As a reminder, here&amp;rsquo;s the existing Run method from our AsyncPump class:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public static void&lt;/span&gt; Run(&lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Task&lt;/span&gt;&amp;gt; asyncMethod) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt; prevCtx = &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.Current; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;try &lt;br /&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt; syncCtx = &lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SingleThreadSynchronizationContext&lt;/span&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.SetSynchronizationContext(syncCtx); &lt;br /&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt; t = asyncMethod(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t.ContinueWith(delegate { syncCtx.Complete(); }, &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;TaskScheduler&lt;/span&gt;.Default); &lt;br /&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; syncCtx.RunOnCurrentThread(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t.GetAwaiter().GetResult(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;finally&lt;/span&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.SetSynchronizationContext(prevCtx); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Most of this will remain the same for our new Action-based variant.&amp;nbsp; In fact, for the new one, we primarily just need to delete all the code having to do with the returned task, since there isn&amp;rsquo;t one, and all notion of completion is being handled by the OperationStarted and OperationCompleted methods we added to the context.&amp;nbsp; We do surround the asyncMethod invocation with calls to OperationStarted and OperationCompleted, just in case the asyncMethod is actually just a void method and not an &amp;ldquo;async void&amp;rdquo; method, in which case we need to make sure the operation count is greater than 0 for the duration of the invocation in order to avoid races that could result if the delegate invoked other async void methods.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public static void&lt;/span&gt; Run(&lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Action&lt;/span&gt; asyncMethod) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt; prevCtx = &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.Current; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;try&lt;/span&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt; syncCtx = &lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SingleThreadSynchronizationContext&lt;/span&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.SetSynchronizationContext(syncCtx); &lt;br /&gt; &lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;strong&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; syncCtx.OperationStarted(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; asyncMethod(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; syncCtx.OperationCompleted();&lt;/strong&gt; &lt;br /&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; syncCtx.RunOnCurrentThread(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;finally&lt;/span&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;SynchronizationContext&lt;/span&gt;.SetSynchronizationContext(prevCtx); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That&amp;rsquo;s it. We&amp;rsquo;re now able to use our AsyncPump to run &amp;ldquo;async void&amp;rdquo; methods synchronously with all continuations executed on the current thread, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static void&lt;/span&gt; Main() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;AsyncPump&lt;/span&gt;.Run((&lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Action&lt;/span&gt;)FooAsync); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static async void&lt;/span&gt; FooAsync() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Foo1Async(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt; Foo2Async(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Foo3Async(); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static async void&lt;/span&gt; Foo1Async() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Task&lt;/span&gt;.Delay(1000); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Console&lt;/span&gt;.WriteLine(1); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static async&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Task&lt;/span&gt; Foo2Async() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Task&lt;/span&gt;.Delay(1000); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Console&lt;/span&gt;.WriteLine(2); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: x-small;" size="2"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static async void&lt;/span&gt; Foo3Async() &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Task&lt;/span&gt;.Delay(1000); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #4bacc6;" color="#4bacc6"&gt;Console&lt;/span&gt;.WriteLine(3); &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Happy async&amp;rsquo;ing.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10263555" width="1" height="1"&gt;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-26-35-55/AsyncPump_2E00_cs" length="6129" type="application/octet-stream" /><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Advanced APM Consumption in Async Methods</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/01/23/10259822.aspx</link><pubDate>Mon, 23 Jan 2012 23:39:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10259822</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10259822</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10259822</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/01/23/10259822.aspx#comments</comments><description>&lt;p&gt;I’ve &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/09/9716439.aspx"&gt;previously blogged&lt;/a&gt; about how to expose existing Asynchronous Programming Model (APM) implementations as Task-based methods.&amp;#160; This can be done manually using a TaskCompletionSource&amp;lt;TResult&amp;gt;, or it can be done using the built-in wrapper provided in TPL via the Task.Factory.FromAsync method.&amp;#160; By creating a Task-based wrapper for such BeginXx/EndXx method pairs, APM implementations become consumable in async methods in C# and Visual Basic: since Tasks are awaitable, any operation exposed as a Task is then inherently awaitable.&lt;/p&gt;  &lt;p&gt;What I haven’t before discussed is how you can consume an APM implementation without wrapping it in a Task, and that’s what I’ll do in this blog post.&amp;#160; What follows is an advanced approach with the only benefit being potentially reduced overheads, and the resulting performance gains are really only relevant in extreme situations.&amp;#160; But such situations do exist, primarily in high-throughput server scenarios.&amp;#160; Further, the techniques involved here are interesting regardless of whether you decide to use them in practice (I &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx"&gt;previously discussed&lt;/a&gt; a similar approach specifically geared towards sockets).&amp;#160; Without further ado…&lt;/p&gt;  &lt;p&gt;The key to this approach is that the C# and Visual Basic compilers support awaiting things other than Tasks, and in fact support &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx"&gt;awaiting anything&lt;/a&gt; that follows the right pattern.&amp;#160; We can take advantage of that to implement a custom awaitable geared explicitly towards optimizing performance when consuming APM implementations.&amp;#160; For very high-throughput workloads, allocations and the resulting garbage collections can lead to noticeable overheads, and thus we want to minimize allocations as much as possible.&amp;#160; In particular, there are many APM implementations that can complete their processing synchronously (i.e. during the BeginXx method), e.g. if you asynchronously retrieve a value that happens to already be buffered or cached, it’s possible to synchronously satisfy the request from that buffer or cache, rather than performing I/O to retrieve or generate it.&amp;#160; For situations where it’s possible for requests to be satisfied synchronously, it’s common that these synchronous code paths become hot paths, and as such we want to avoid as much overhead as possible on them.&lt;/p&gt;  &lt;p&gt;One of the tricks I’ve mentioned in the past for minimizing allocations is caching and reusing the objects used to represent asynchronous operations.&amp;#160; For example, in the case of async methods with C# and Visual Basic, the async method infrastructure &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx"&gt;caches common Task and Task&amp;lt;TResult&amp;gt; instances&lt;/a&gt; that it can use repeatedly (if the right conditions are met) as the return object from an async method. As another example (and an internal implementation detail, so this could of course change in the future), MemoryStream’s ReadAsync method will remember the last Task&amp;lt;int&amp;gt; it returned for a successful read, and if the subsequent ReadAsync operation completes with the same number of bytes, it can reuse and return that same cached Task&amp;lt;int&amp;gt; rather than instantiating a new one.&amp;#160; We can take advantage of this same kind of optimization in order to minimize allocations when consuming APM implementations directly.&lt;/p&gt;  &lt;p&gt;To do so, we’ll develop an “AsyncApmAdapter” type that implements the await pattern and that we can reuse over and over again for sequential APM calls.&amp;#160; This type will be awaitable, with its GetResult method returning the IAsyncResult for the operation.&amp;#160; We’ll pass an adapter instance as the object state into the BeginXx method, along with an AsyncCallback that will configure the adapter instance appropriately when the asynchronous operation completes.&amp;#160; We’ll then await the adapter and pass the resulting IAsyncResult into the EndXx method. This yields the following pattern:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; adapter = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;();        &lt;br /&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;...       &lt;br /&gt;BeginXx(..., &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;.Callback, adapter);        &lt;br /&gt;EndXx(&lt;font color="#0000ff"&gt;await&lt;/font&gt; adapter);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To use my favorite looping example, if we wanted to write a read / write loop to copy from one stream to another using Stream.Begin/EndRead and Stream.Begin/EndWrite, that could look like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;static async&lt;/font&gt; &lt;font color="#4bacc6"&gt;Task&lt;/font&gt; CopyStreamAsync(&lt;font color="#4bacc6"&gt;Stream&lt;/font&gt; source, &lt;font color="#4bacc6"&gt;Stream&lt;/font&gt; dest)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; &lt;/font&gt;adapter = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;();&lt;/strong&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; &lt;/font&gt;buffer = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#0000ff"&gt;byte&lt;/font&gt;[0x1000];        &lt;br /&gt;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;while&lt;/font&gt;&lt;/font&gt;(&lt;font color="#0000ff"&gt;true&lt;/font&gt;)        &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; source.BeginRead(buffer, 0, buffer.Length,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;&lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;.Callback, adapter&lt;/strong&gt;);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;int &lt;/font&gt;&lt;/font&gt;numRead = source.EndRead(&lt;strong&gt;&lt;font color="#0000ff"&gt;await&lt;/font&gt; adapter&lt;/strong&gt;);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;if &lt;/font&gt;&lt;/font&gt;(numRead == 0) &lt;font color="#0000ff"&gt;break&lt;/font&gt;;        &lt;br /&gt;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dest.BeginWrite(buffer, 0, numRead,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;&lt;strong&gt;&lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;&lt;/strong&gt;.Callback, adapter&lt;/strong&gt;);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dest.EndWrite(&lt;strong&gt;&lt;font color="#0000ff"&gt;await&lt;/font&gt; adapter&lt;/strong&gt;);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;      &lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Note that we’ve only had to allocate the one AsyncApmAdapter instance, which we can reuse over and over again as we make Begin/EndRead and Begin/EndWrite APM calls to the source and destination streams.&lt;/p&gt;  &lt;p&gt;How do we achieve such magic? Let’s start by defining our adapter type, which will act both as an awaitable and as an awaiter:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;internal sealed class&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncApmAdapter &lt;/font&gt;GetAwaiter() {&lt;font color="#0000ff"&gt; return&lt;/font&gt; this; }        &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; public bool&lt;/font&gt; IsCompleted { &lt;font color="#0000ff"&gt;get &lt;/font&gt;{ ... } }        &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; public void&lt;/font&gt; OnCompleted(&lt;font color="#4bacc6"&gt;Action&lt;/font&gt; continuation) { ... }          &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; public&lt;/font&gt; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; GetResult() { ... }            &lt;br /&gt;            &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ... &lt;font color="#008040"&gt;// fields&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;       &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We’ll need a few fields in our adapter.&amp;#160; First, we’ll need to be able to store an IAsyncResult for the APM side of things, and second, we’ll need to be able to store the Action continuation delegate that will be supplied by the async method when awaiting on our adapter instance.&amp;#160; We’re also going to need a dummy Action delegate that we can use as a sentinel, a marker to help synchronize (we’ll see where and why shortly).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; _asyncResult;        &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;/font&gt;&lt;font color="#4bacc6"&gt;Action&lt;/font&gt; _continuation;        &lt;br /&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;private&lt;/font&gt; &lt;/font&gt;&lt;font color="#0000ff"&gt;readonly static&lt;/font&gt; &lt;font color="#4bacc6"&gt;Action&lt;/font&gt; CALLBACK_RAN = () =&amp;gt; { };&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As used in the earlier example, our adapter exposes a static Callback field of type AsyncCallback; by creating and caching this delegate once, we can use it for all invocations (it doesn’t mutate any shared state).&amp;#160; It is the responsibility of this AsyncCallback to mutate supplied the adapter instance (passed in via the object state) when the async operation completes.&amp;#160; If the operation completes synchronously (such that CompletedSynchronously is true), the only thing the callback needs to do is store the IAsyncResult for the operation into the adapter.&amp;#160; If, however, the operation completes asynchronously, then we need to do a bit more.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public readonly static&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncCallback&lt;/font&gt; Callback = asyncResult =&amp;gt;         &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;adapter = (&lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;) asyncResult.AsyncState;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;adapter._asyncResult = asyncResult;       &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;if&lt;/font&gt; (!asyncResult.CompletedSynchronously)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Action&lt;/font&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt; continuation = adapter._continuation ??        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Interlocked&lt;/font&gt;.CompareExchange(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ref&lt;/font&gt; adapter._continuation, CALLBACK_RAN, &lt;font color="#0000ff"&gt;null&lt;/font&gt;);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (continuation != &lt;font color="#0000ff"&gt;null&lt;/font&gt;) continuation();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;font size="2"&gt;&lt;font face="Consolas"&gt;         &lt;br /&gt;&lt;/font&gt;&lt;font face="Consolas"&gt;};&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In the case where we’re completing asynchronously, we’re potentially racing with the call site that will be checking whether the async method should continue running synchronously (via the awaiter’s IsCompleted) or whether it should yield, suspending the async method’s execution (via the awaiter’s OnCompleted).&amp;#160; As such, there’s some coordination that needs to happen between the callback and IsCompleted / OnCompleted.&amp;#160; The OnCompleted method will set the _continuation field to the Action provided by async method infrastructure.&amp;#160; As such, if _continuation is already non-null, then OnCompleted was already invoked, and we thus need to invoke the supplied Action _continuation here.&amp;#160; If, however, _continuation is null, we need to set it to our sentinel Action delegate (CALLBACK_RUN)… this will indicate to IsCompleted / OnCompleted that the async operation has already finished, and thus IsCompleted / OnCompleted needs to take care of continuing the execution.&lt;/p&gt;  &lt;p&gt;IsCompleted’s job is relatively simple.&amp;#160; The _asyncResult field starts out on the adapter as null.&amp;#160; If it’s still null when IsCompleted is accessed, then we must yield so that execution can continue asynchronously.&amp;#160; If the _asyncResult field is non-null when IsCompleted is accessed, that means the callback has at least started running (and filled in _asyncResult as part of that), but we don’t know whether it’s finished or not.&amp;#160; So, we check one of two additional conditions.&amp;#160; If the IAsyncResult’s CompletedSynchronously is true, then we know the callback completed, because it was invoked synchronously as part of the call to BeginXx, and we’re not accessing IsCompleted until after BeginXx returns.&amp;#160; If, however, CompletedSynchronously is false, then we’ll check the _continuation field itself.&amp;#160; Remember that the callback will try to set the _continuation field to the CALLBACK_RAN sentinel, so here in IsCompleted if _continuation is already CALLBACK_RAN, then we know that, well, the callback ran.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public bool&lt;/font&gt; IsCompleted         &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt;         &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; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; iar = _asyncResult;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; iar != &lt;font color="#0000ff"&gt;null&lt;/font&gt; &amp;amp;&amp;amp;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (iar.CompletedSynchronously ||&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _continuation == CALLBACK_RAN);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;There are some benign races here.&amp;#160; It’s possible that the async operation could be completing concurrently with IsCompleted being called, and that’s ok… in the rare case where the operation has already completed but where IsCompleted doesn’t notice, it’ll simply return false, and we’ll just rely on OnCompleted to handle synchronizing with the callback.&lt;/p&gt;  &lt;p&gt;Now on to OnCompleted.&amp;#160; In the await pattern, OnCompleted is invoked to schedule the Action continuation delegate.&amp;#160; To do so in our case, ideally OnCompleted can just store the provided Action into the _continuation field, such that when the async operation completes, the callback will invoke _continuation (as we saw earlier).&amp;#160; However, it’s possible that IsCompleted returns false, but concurrently with invoking IsCompleted and OnCompleted, the operation then completes.&amp;#160; Thus, OnCompleted must be able to deal with the case where the operation has already completed by the time OnCompleted is invoked. However, OnCompleted must not invoke the delegate synchronously, even if it determines that the async operation has already completed, otherwise we risk “stack dives”.&amp;#160; So, OnCompleted checks whether the callback has already tried to pick up the _continuation delegate, which OnCompleted knows by seeing if _continuation is CALLBACK_RAN.&amp;#160; If it’s not yet CALLBACK_RAN, then it’ll simply store the supplied continuation delegate into _continuation.&amp;#160; If, however, it is already CALLBACK_RAN, then it’ll use a Task to schedule the continuation to run asynchronously.&amp;#160; And, for correctness, any writes here need to happen as part of an atomic compare-and-swap operation.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public void&lt;/font&gt; OnCompleted(&lt;font color="#4bacc6"&gt;Action&lt;/font&gt; continuation)         &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (_continuation == CALLBACK_RAN ||         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Interlocked&lt;/font&gt;.CompareExchange(        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ref&lt;/font&gt; _continuation, continuation, &lt;font color="#0000ff"&gt;null&lt;/font&gt;) == CALLBACK_RAN)         &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; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#4bacc6"&gt;Task&lt;/font&gt;.Run(continuation);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;}       &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Finally, we need to implement GetResult.&amp;#160; As I mentioned previously, GetResult’s role will be to return the stored IAsyncResult.&amp;#160; However, we also want to be able to reuse this adapter instance over and over, which means we need to reset its state after each operation completes, and GetResult is a good place to do that:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; GetResult() {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; result = _asyncResult;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; _asyncResult = null;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; _continuation = null;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; result;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That’s it for the implementation.&amp;#160; A bit tricky, certainly, but relatively little code, and it can provide for improved performance in those extreme situations I alluded to earlier.&amp;#160; Of course, that potential overhead reduction comes at the price of readability.&amp;#160; For example, with this approach you can no longer use the async operation as an expression.&amp;#160; To address that, a colleague of mine, &lt;a href="http://blogs.msdn.com/b/ericeil/"&gt;Eric Eilebrecht&lt;/a&gt;, suggested a cute hack: implement a GetAwaiter extension method on IAsyncResult:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public static class&lt;/font&gt; &lt;font color="#4bacc6"&gt;IAsyncResultExtensions&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;public static&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncApmAdapter &lt;/font&gt;GetAwaiter(&lt;font color="#0000ff"&gt;this&lt;/font&gt; &lt;font color="#4bacc6"&gt;IAsyncResult&lt;/font&gt; iar)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;return&lt;/font&gt; (&lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;)iar.AsyncState;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font size="2" face="Consolas"&gt;}       &lt;br /&gt;&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With that, instead of writing:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;BeginXx(..., &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;.Callback, adapter);        &lt;br /&gt;EndXx(&lt;font color="#0000ff"&gt;await&lt;/font&gt; adapter);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;you could write:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;EndXx(&lt;font color="#0000ff"&gt;await&lt;/font&gt; BeginXx(..., &lt;font color="#4bacc6"&gt;AsyncApmAdapter&lt;/font&gt;.Callback, adapter));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;thereby regaining some of the expressiveness lost in the approach.&amp;#160; Of course, this extension method only makes sense when the object state is an AsyncApmAdapter used in this manner, so be careful with such an approach.&lt;/p&gt;  &lt;p&gt;Per my comments at the beginning of this post, if you need to consume an APM implementation, converting it into a Task (via Task.Factory.FromAsync or other means) is a great way.&amp;#160; However, if you do find yourself in a position where you’re using an async method to consume an APM implementation, and if it’s crucial to your scenario that you eek out every last bit of performance possible, you could consider an approach like that outlined in this post.&amp;#160; As with any micro-optimization that leads to (slightly) less readable code, make sure it’s worthwhile before paying for it, and measure, measure, measure.&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10259822" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Await, SynchronizationContext, and Console Apps: Part 2</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx</link><pubDate>Sun, 22 Jan 2012 00:49:09 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10259307</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10259307</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10259307</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx#comments</comments><description>&lt;p&gt;Yesterday, I &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx"&gt;blogged&lt;/a&gt; about how you can implement a custom SynchronizationContext in order to pump the continuations used by async methods so that they may be processed on a single, dedicated thread.&amp;#160; I also highlighted that this is basically what UI frameworks like Windows Forms and Windows Presentation Foundation do with their message pumps.&lt;/p&gt;  &lt;p&gt;Now that we understand the mechanics of how these things work, it’s worth pointing out that we can achieve the same basic semantics without writing our own custom SynchronizationContext.&amp;#160; Instead, we can use one that already exists in the .NET Framework: DispatcherSynchronizationContext.&amp;#160; Through its Dispatcher class and its &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx"&gt;PushFrame&lt;/a&gt; method, WPF provides the ability to (as described in MSDN) “enter an execute loop” that “processes pending work items.”&amp;#160; This is exactly what our custom SynchronizationContext was doing with its usage of BlockingCollection&amp;lt;T&amp;gt;, so we can just use WPF’s support instead of developing our own. (You might ask then why I started by describing how to do it manually and writing my own to exemplify it.&amp;#160; I do so because I think it’s important to really understand how things work; I typically find that developers write better higher-level code if they have the right mental model for what’s happening under the covers, allowing them to better reason about bugs, about performance, about reliability, and the like.)&lt;/p&gt;  &lt;p&gt;Below you can see how few lines of code it takes to achieve this support.&amp;#160; (To compile this code, you’ll need to reference WindowsBase.dll to bring in the relevant WPF types.)&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; System;        &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; &lt;/font&gt;System.Threading;        &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; &lt;/font&gt;System.Threading.Tasks;        &lt;br /&gt;&lt;font size="2" face="Consolas"&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; &lt;/font&gt;System.Windows.Threading;        &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;public static class&lt;/font&gt; &lt;font color="#4bacc6"&gt;AsyncPump&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void&lt;/font&gt; Run(&lt;font color="#4bacc6"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#4bacc6"&gt;Task&lt;/font&gt;&amp;gt; func)        &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; &lt;font color="#0000ff"&gt;if&lt;/font&gt; (func == &lt;font color="#0000ff"&gt;null&lt;/font&gt;) &lt;font color="#0000ff"&gt;throw new&lt;/font&gt; &lt;font color="#4bacc6"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#c0504d"&gt;&amp;quot;func&amp;quot;&lt;/font&gt;);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; prevCtx = &lt;font color="#4bacc6"&gt;SynchronizationContext&lt;/font&gt;.Current;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;try&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; syncCtx = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#4bacc6"&gt;DispatcherSynchronizationContext&lt;/font&gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;SynchronizationContext&lt;/font&gt;.SetSynchronizationContext(syncCtx);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; t = func();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (t == &lt;font color="#0000ff"&gt;null&lt;/font&gt;) &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#4bacc6"&gt;InvalidOperationException&lt;/font&gt;();        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var &lt;/font&gt;frame = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#4bacc6"&gt;DispatcherFrame&lt;/font&gt;();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; t.ContinueWith(_ =&amp;gt; { frame.Continue = &lt;font color="#0000ff"&gt;true&lt;/font&gt;; },         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;TaskScheduler&lt;/font&gt;.Default);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;Dispatcher&lt;/font&gt;.PushFrame(frame);        &lt;br /&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; t.GetAwaiter().GetResult();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;finally&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#4bacc6"&gt;SynchronizationContext&lt;/font&gt;.SetSynchronizationContext(prevCtx);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In short, we instantiate a DispatcherSynchronizationContext and publish it to be Current on the current thread; this is what enables the awaits inside of the async method being processed to queue their continuations back to this thread and this thread’s Dispatcher.&amp;#160; Then we instantiate a DispatcherFrame, which represents an execute loop for WPF’s message pump.&amp;#160; We use a continuation to signal to that DispatcherFrame when it should exit its loop (i.e. when the Task completes).&amp;#160; And then we start the frame’s execute loop via the PushFrame method.&lt;/p&gt;  &lt;p&gt;All in all, just a few lines of code to achieve some powerful and useful behavior.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10259307" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Implementing a SynchronizationContext.SendAsync method</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259082.aspx</link><pubDate>Sat, 21 Jan 2012 00:23:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10259082</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10259082</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10259082</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259082.aspx#comments</comments><description>&lt;p&gt;I recently saw two unrelated questions, the answers to which combine to form a potentially useful code snippet.&lt;/p&gt;
&lt;p&gt;The first question was about SynchronizationContext.&amp;nbsp; SynchronizationContext provides a Post method, which asynchronously schedules the supplied delegate and object state to be executed according to the SynchronizationContext&amp;rsquo;s whims.&amp;nbsp; However, Post returns void, so there&amp;rsquo;s no built-in way to know when the operation has completed.&amp;nbsp; SynchronizationContext also provides a Send method, which won&amp;rsquo;t return until the delegate has been executed; that means that while you do have a built-in way to know when the operation has completed, it&amp;rsquo;s also a synchronous operation, blocking the current thread.&amp;nbsp; The question then was whether there was a way to achieve the asynchronous behavior of Post but with the ability of Send to know when the operation has completed, e.g. an asynchronous Send:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;public Task SendAsync(SendOrPostCallback d, object state);&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The second question was about implementing asynchronous operations that return Tasks but without using async and await.&amp;nbsp; In effect, the questioner wanted to create a Task-returning method to represent an existing non-Task-based mechanism they were already using.&lt;/p&gt;
&lt;p&gt;So, let&amp;rsquo;s try to satisfy both questions by implementing SendAsync using Post as the underlying mechanism that we&amp;rsquo;ll wrap with a Task.&lt;/p&gt;
&lt;p&gt;The first thing we need is a TaskCompletionSource&amp;lt;T&amp;gt;.&amp;nbsp; TaskCompletionSource&amp;lt;T&amp;gt; is the mechanism within the Task Parallel Library that exists to create tasks that you can explicitly complete. Rather than creating a Task that&amp;rsquo;s associated with a delegate and whose completion is then tied to that delegate&amp;rsquo;s execution, TaskCompletionSource&amp;lt;T&amp;gt; create as task that&amp;rsquo;s not associated with a delegate, and it gives you methods like SetResult and SetException that allow you to complete the task when and how you see fit.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This capability makes TaskCompletionSource ideal for wrapping existing operations. The idea is that we create a TaskCompletionSource&amp;lt;T&amp;gt; and we then use its Task property to get at the task that we can manually complete via the TaskCompletionSource.&amp;nbsp; We then launch the underlying operation being wrapped, and when it completes, we either invoke the SetResult method with the result of the operation completing successfully, or we invoke the SetException method with the error that resulted from its failure. We can follow this pattern to implement SendAsync by wrapping Post:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;public static Task SendAsync( &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this SynchronizationContext context, SendOrPostCallback d, object state) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var tcs = new TaskCompletionSource&amp;lt;bool&amp;gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; context.Post(delegate { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; d(state); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; tcs.SetResult(true); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; catch(Exception e) { tcs.SetException(e); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }, null); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return tcs.Task; &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here, the delegate we pass to Post invokes the original delegate, but it does so wrapped in a try/catch block.&amp;nbsp; If the invocation of the original delegate succeeds, we complete the Task successfully, and if an exception occurred from invoking the delegate, we complete the task with the thrown error. With this extension method on SynchronizationContext, we can now write code that uses await to asynchronously wait for an operation sent to a particular SynchronizationContext to complete.&amp;nbsp; And while there are various things we could do to improve the performance of this method slightly (e.g. by taking advantage of Post&amp;rsquo;s object state parameter rather than using a closure), overall it&amp;rsquo;s a fine representation of how you can create Task-based wrappers for existing mechanisms.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10259082" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Await, SynchronizationContext, and Console Apps</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx</link><pubDate>Fri, 20 Jan 2012 23:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10259049</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10259049</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10259049</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx#comments</comments><description>&lt;p&gt;When I discuss the new async language features of C# and Visual Basic, one of the attributes I ascribe to the await keyword is that it &amp;ldquo;tries to bring you back to where you were.&amp;rdquo; For example, if you use await on the UI thread of your WPF application, the code that comes after the await completes should run back on that same UI thread.&lt;/p&gt;
&lt;p&gt;There are several mechanisms that are used by the async/await infrastructure under the covers to make this marshaling work: SynchronizationContext and TaskScheduler. While the transformation is much more complicated than what I&amp;rsquo;m about to show, logically you can think of the following code:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;await&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; FooAsync();&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;RestOfMethod();&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;as being similar in nature to this:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; t = FooAsync();&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; currentContext = &lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;.Current;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;t.ContinueWith(&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;delegate&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; (currentContext == &lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;null&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;RestOfMethod();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff; font-size: 10pt;" color="#0000ff"&gt;else&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&lt;/span&gt;currentContext.Post(&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;delegate&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; { RestOfMethod(); }, &lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;null&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;}, &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;TaskScheduler&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;.Current);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In other words, before the async method yields to asynchronously wait for the Task &amp;lsquo;t&amp;rsquo;, we capture the current SynchronizationContext. When the Task being awaited completes, a continuation will run the remainder of the asynchronous method. If the captured SynchronizationContext was null, then RestOfMethod() will be executed in the original TaskScheduler (which is often TaskScheduler.Default, meaning the ThreadPool). If, however, the captured context wasn&amp;rsquo;t null, then the execution of RestOfMethod() will be posted to the captured context to run there.&lt;/p&gt;
&lt;p&gt;Both SynchronizationContext and TaskScheduler are abstractions that represent a &amp;ldquo;scheduler&amp;rdquo;, something that you give some work to, and it determines when and where to run that work. There are many different forms of schedulers. For example, the ThreadPool is a scheduler: you call ThreadPool.QueueUserWorkItem to supply a delegate to run, that delegate gets queued, and one of the ThreadPool&amp;rsquo;s threads eventually picks up and runs that delegate. Your user interface also has a scheduler: the message pump. A dedicated thread sits in a loop, monitoring a queue of messages and processing each; that loop typically processes messages like mouse events or keyboard events or paint events, but in many frameworks you can also explicitly hand it work to do, e.g. the Control.BeginInvoke method in Windows Forms, or the Dispatcher.BeginInvoke method in WPF.&lt;/p&gt;
&lt;p&gt;SynchronizationContext, then, is just an abstract class that can be used to represent such a scheduler. The base class exposes several virtual methods, but we&amp;rsquo;ll focus on just one: Post. Post accepts a delegate, and the implementation of Post gets to decide when and where to run that delegate. The default implementation of SynchronizationContext.Post just turns around and passes it off to the ThreadPool via QueueUserWorkItem. But frameworks can derive their own context from SynchronizationContext and override the Post method to be more appropriate to the scheduler being represented. In the case of Windows Forms, for example, the WindowsFormsSynchronizationContext implements Post to pass the delegate off to Control.BeginInvoke. For DispatcherSynchronizationContext in WPF, it calls to Dispatcher.BeginInvoke. And so on.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s how await &amp;ldquo;brings you back to where you were.&amp;rdquo; It asks for the SynchronizationContext that&amp;rsquo;s representing the current environment, and then when the await completes, the continuation is posted back to that context. It&amp;rsquo;s up to the implementation of the captured context to run the delegate in the right place, e.g. in the case of a UI app, that means running the delegate on the UI thread. This explanation also helps to highlight what happens if the environment didn&amp;rsquo;t set a SynchronizationContext onto the current thread (and if there&amp;rsquo;s not special TaskScheduler, as there isn&amp;rsquo;t in this case). If the context comes back as null, then the continuation could run &amp;ldquo;anywhere&amp;rdquo;. I put anywhere in quotes because obviously the continuation can&amp;rsquo;t run &amp;ldquo;anywhere,&amp;rdquo; but logically you can think of it like that&amp;hellip; it&amp;rsquo;ll either end up running on the same thread that completed the awaited task, or it&amp;rsquo;ll end up running in the ThreadPool.&lt;/p&gt;
&lt;p&gt;All of the UI application types you can create in Visual Studio will end up having a special SynchronizationContext published on the UI thread. Windows Forms, Windows Presentation Foundation, Metro style apps&amp;hellip; they all have one. But there&amp;rsquo;s one common kind of application that doesn&amp;rsquo;t have a SynchronizationContext: console apps. When your console application&amp;rsquo;s Main method is invoked, SynchronizationContext.Current will return null. That means that if you invoke an asynchronous method in your console app, unless you do something special, your asynchronous methods will not have thread affinity: the continuations within those asynchronous methods could end up running &amp;ldquo;anywhere.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;As an example, consider this application:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;using&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; System;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;using&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; System.Collections.Generic;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;using&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; System.Threading;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;using&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; System.Threading.Tasks;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af; font-size: 10pt;" color="#2b91af"&gt;Program&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; Main()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;DemoAsync().Wait();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;async&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Task&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; DemoAsync()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; d = &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Dictionary&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;, &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;gt;();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;for&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; (&lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; i = 0; i &amp;lt; 10000; i++)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; id = &lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Thread&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;.CurrentThread.ManagedThreadId;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; count;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;d[id] = d.TryGetValue(id, &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;out&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; count) ? count+1 : 1;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Task&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;.Yield();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;foreach&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; (&lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; pair &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;in&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; d) &lt;/span&gt;&lt;span&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Console&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt;.WriteLine(pair);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Here I&amp;rsquo;ve created a dictionary that maps thread IDs to the number of times we encountered that particular thread. For thousands of iterations, I get the current thread&amp;rsquo;s ID and increment the appropriate element of my histogram, then yield. The act of yielding will use a continuation to run the remainder of the method. Here&amp;rsquo;s some representative output I see from executing this app:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[1, 1]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[3, 2687]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[4, 2399]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[5, 2397]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[6, 2516]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;Press any key to continue . . .&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We can see here that the execution of this code used 5 threads over the course of its run. Interestingly, one of the threads only had one hit. Can you guess which thread that was? It&amp;rsquo;s the thread running the Main method of the console app. When we call DemoAsync, it runs synchronously until the first await the yields, so the first time we check the ManagedThreadId for the current thread, we&amp;rsquo;re still on the thread that invoked DemoAsync. Once we hit the await, the method returns back to Main(), which then blocks waiting on the returned Task to complete. The continuations used by the remainder of the async method&amp;rsquo;s execution would have been posted to SynchronizationContext.Current, except that it a console app, it&amp;rsquo;s null (unless you explicitly override that with SynchronizationContext.SetSynchronizationContext). So the continuations just get scheduled to run on the ThreadPool. That&amp;rsquo;s where the rest of those threads are coming from&amp;hellip; they&amp;rsquo;re all ThreadPool threads.&lt;/p&gt;
&lt;p&gt;Is it a problem then that using async like this in a console app might end up running continuations on ThreadPool threads? I can&amp;rsquo;t answer that, because the answer is entirely up to what kind of semantics you need in your application. For many applications, this will be perfectly reasonable behavior. Other applications, however, may require thread affinity, such that all of the continuations run on the same thread. For example, if you invoked multiple async methods concurrently, you might want all the continuations they use to be serialized, and an easy way to guarantee that is to ensure that only one thread is used for executing all of the continuations. If your application does demand such behavior, are you out of luck? Thankfully, the answer is &amp;lsquo;no&amp;rsquo;. You can add such behavior yourself.&lt;/p&gt;
&lt;p&gt;If you&amp;rsquo;ve made it this far in reading, hopefully the components of a solution here have started to become obvious. You effectively need a message pump, a scheduler, something that runs on the Main thread of your app processing a queue of work. And you need a SynchronizationContext (or a TaskScheduler if you prefer) that feeds the await continuations into that queue. With that framework in place, let&amp;rsquo;s build a solution.&lt;/p&gt;
&lt;p&gt;First, we need our SynchronizationContext. As described in the previous paragraph, we&amp;rsquo;ll need a queue to store the work to be done. The work provided to the Post method comes in the form of two objects: a SendOrPostCallback delegate, and an object state that is meant to be passed into that delegate when it&amp;rsquo;s invoked. As such, we&amp;rsquo;ll have our queue store a KeyValuePair&amp;lt;TKey,TValue&amp;gt; of these two objects. What kind of queue data structure should we use? We need something ideally suited to handle producer/consumer scenarios, as our asynchronous method will be &amp;ldquo;producing&amp;rdquo; these pairs of work, and our pumping loop will need to be &amp;ldquo;consuming&amp;rdquo; them from the queue and executing them. .NET 4 saw the introduction of the perfect type for the job: BlockingCollection&amp;lt;T&amp;gt;. BlockingCollection&amp;lt;T&amp;gt; is a data structure that encapsulates not only a queue, but also all of the synchronization necessary to coordinate between a producer adding elements to that queue and a consumer removing them, including blocking the consumer attempting a removal while the queue is empty.&lt;/p&gt;
&lt;p&gt;With that, the pieces fall into place: a BlockingCollection&amp;lt;KeyValuePair&amp;lt;SendOrPostCallback,object&amp;gt;&amp;gt; instance; a Post method that adds to the queue; another method that sits in a consuming loop, removing each work item and processing it; and finally another method that lets the queue know that no more work will arrive, allowing the consuming loop to exit once the queue is empty.&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;sealed&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SingleThreadSynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt; : &lt;/span&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af; font-size: 10pt;" color="#2b91af"&gt;SynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;readonly&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;BlockingCollection&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;KeyValuePair&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SendOrPostCallback&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;,&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;object&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;gt;&amp;gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;m_queue =&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;BlockingCollection&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;KeyValuePair&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SendOrPostCallback&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;,&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;object&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;gt;&amp;gt;();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;override&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; Post(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SendOrPostCallback&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; d, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;object&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; state)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;m_queue.Add(&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;KeyValuePair&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SendOrPostCallback&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;,&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;object&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;gt;(d, state));&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; RunOnCurrentThread()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;KeyValuePair&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SendOrPostCallback&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;object&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;gt; workItem;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;while&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;(m_queue.TryTake(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;out&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; workItem, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Timeout&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;.Infinite))&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;workItem.Key(workItem.Value);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;span&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="color: #000000;" color="#000000"&gt; Complete() { m_queue.CompleteAdding(); }&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&amp;hellip;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Believe it or not, we&amp;rsquo;re already half done with our solution. We need to instantiate one of these contexts and set it as current onto the current thread, so that when we then invoke the asynchronous method, that method&amp;rsquo;s awaits will see this context as Current. We need to alert the context to when there won&amp;rsquo;t be any more work arriving, which we can do by using a continuation to call Complete on our context when the Task returned from the async method is compelted. We need to run the processing loop via the context&amp;rsquo;s RunOnCurrentThread method. And we need to propagate any exceptions that may have occurred during the async method&amp;rsquo;s processing. All in all, it&amp;rsquo;s just a few lines:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; Run(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Func&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Task&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;gt; func)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; prevCtx = &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;.Current;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff; font-size: 10pt;" color="#0000ff"&gt;try&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; syncCtx = &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SingleThreadSynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;.SetSynchronizationContext(syncCtx);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;var&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; t = func();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;t.ContinueWith(&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;delegate&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; { syncCtx.Complete(); }, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;TaskScheduler&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;.Default);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;syncCtx.RunOnCurrentThread();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;t.GetAwaiter().GetResult();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;finally&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; { &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;SynchronizationContext&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;.SetSynchronizationContext(prevCtx); }&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s it. With our solution now available, I can change the Main method of my demo console app from:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;static void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; Main()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;DemoAsync().Wait();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;to instead use our new AsyncPump.Run method:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;&lt;span style="font-size: 10pt;"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; Main()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;AsyncPump&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;.Run(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;async&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff; font-size: 10pt;" color="#0000ff"&gt;delegate&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;await&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt; DemoAsync();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="font-size: 10pt;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt;"&gt;});&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; background-position: 0% 0%; mso-highlight: white;"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;When I then run my app again, this time I get the following output:&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;[1, 10000]&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="list-style-type: disc; margin: 0in 0in 0pt 0.5in;" class="Code"&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&lt;span style="color: #000000; font-size: 10pt;" color="#000000"&gt;Press any key to continue . . .&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see, all of the continuations have run on just one thread, the main thread of my console app.&lt;/p&gt;
&lt;p&gt;The AsyncPump sample class described in this post is available as an attachment to this post.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10259049" width="1" height="1"&gt;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-25-90-49/AsyncPump_2E00_cs" length="3322" type="application/octet-stream" /><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Coordination+Data+Structures/">Coordination Data Structures</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>FAQ on Task.Start</title><link>http://blogs.msdn.com/b/pfxteam/archive/2012/01/14/10256832.aspx</link><pubDate>Sun, 15 Jan 2012 02:03:53 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10256832</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10256832</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10256832</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2012/01/14/10256832.aspx#comments</comments><description>&lt;p&gt;Recently I’ve heard a number of folks asking about Task.Start, when and when not to use it, how it behaves,and so forth.&amp;#160; I thought I’d answer some of those questions here in an attempt to clarify and put to rest any misconceptions about what it is and what it does.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;1. Question: When can I use Task.Start?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The Start instance method may be used if and only if the Task is in the Created state (i.e. Task.Status returns TaskStatus.Created).&amp;#160; And the only way a Task can be in the Created state is if the Task were instantiated using one of Task’s public constructors, e.g. &amp;quot;var t = new Task(someDelegate);”.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;2. Question: Should I call Start on a Task created by Task.Run / Task.ContinueWith / Task.Factory.StartNew / TaskCompletionSource / async methods / …?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;No.&amp;#160; Not only shouldn’t you, but you simply can’t… it would fail with an exception. See question #1. The Start method is only applicable to a Task in the Created state.&amp;#160; Tasks created by all of those mentioned means are already beyond the Created state, such that their Task.Status will not return TaskStatus.Created, but something else, like TaskStatus.WaitingForActivation, or TaskStatus.Running, or TaskStatus.RanToCompletion.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;3. Question: What does Start actually do?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;It queues the Task to the target TaskScheduler (the parameterless overload of Start targets TaskScheduler.Current).&amp;#160; When you construct a Task with one of Task’s constructors, the Task is inactive: it has not been given to any scheduler yet, and thus there’s nothing to actually execute it.&amp;#160; If you never Start a Task, it’ll never be queued, and so it’ll never complete.&amp;#160; To get the Task to execute, it needs to be queued to a scheduler, so that the scheduler can execute it when and where the scheduler sees fit to do so.&amp;#160; The act of calling Start on a Task will twiddle some bits in the Task (e.g. changing its state from Created to WaitingToRun) and will then pass the Task to the target scheduler via the TaskScheduler’s QueueTask method.&amp;#160; At that point, the task’s future execution is in the hands of the scheduler, which should eventually execute the Task via the TaskScheduler’s TryExecuteTask method.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;4. Question: Can I call Start more than once on the same Task?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;No.&amp;#160; A Task may only transition out of the Created state once, and Start transitions a Task out of the Created state: therefore, Start may only be used once.&amp;#160; Any attempts to call Start on a Task not in the Created state will result in an exception.&amp;#160; The Start method employs synchronization to ensure that the Task object remains in a consistent state even if Start is called multiple times concurrently… only one of those calls may succeed.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;5. Question: What’s the difference between using Task.Start and Task.Factory.StartNew?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Task.Factory.StartNew is shorthand for new’ing up a Task and Start’ing it.&amp;#160; So, the following code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;var t = Task.Factory.StartNew(someDelegate);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;is functionally equivalent to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;var t = new Task(someDelegate);     &lt;br /&gt;t.Start();&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Performance-wise, the former is slightly more efficient.&amp;#160; As mentioned in response to question #3, Start employs synchronization to ensure that the Task instance on which Start is being called hasn’t already been started, or isn’t concurrently being started.&amp;#160; In contrast, the implementation of StartNew knows that no one else could be starting the Task concurrently, as it hasn’t given out that reference to anyone… so StartNew doesn’t need to employ that synchronization.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;6. Question: I’ve heard that Task.Result may also start the Task.&amp;#160; True?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;False.&amp;#160; There are only two ways that a Task in the Created state may transition out of that state:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A CancellationToken was passed into the Task’s constructor, and that token then had or then has cancellation requested.&amp;#160; If the Task is still in the Created state when that happens, it would transition into the Canceled state.&lt;/li&gt;    &lt;li&gt;Start is called on the Task.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;That’s it, and notice that Result is not one of those two.&amp;#160; If you use .Wait() or .Result on a Task in the Created state, the call will block; someone else would need to Start the Task so that it could then be queued to a scheduler, so that the scheduler could eventually execute it, and so that the Task could complete… the blocking call could then complete as well and wake up.&lt;/p&gt;  &lt;p&gt;What you might be thinking of isn’t that .Result could start the task, but that it could potentially “inline” the task’s execution.&amp;#160; If a Task has already been queued to a TaskScheduler, then that Task might still be sitting in whatever data structure the scheduler is using to store queued tasks.&amp;#160; When you call .Result on a Task that’s been queued, the runtime can attempt to inline the Task’s execution (meaning to run the Task on the calling thread) rather than purely blocking and waiting for some other thread used by the scheduler to execute the Task at some time in the future.&amp;#160; To do this, the call to .Result may end up calling the TaskScheduler’s TryExecuteTaskInline method, and it’s up to the TaskScheduler how it wants to handle the request.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;7. Question: Should I return unstarted Tasks from public APIs?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The proper question is “Should I return Tasks in the Created state from public APIs?”&amp;#160; And the answer is “No.”&amp;#160; (I draw the distinction in the question here due to questions #1 and #2 above… the majority of mechanisms for creating a Task don’t permit for Start to be called, and I don’t want folks to get the impression that you must call Start on a Task in order to allow it to be returned from a public API… that is not the case.)&lt;/p&gt;  &lt;p&gt;The fundamental idea here is this.&amp;#160; When you call a normal synchronous method, the invocation of that method begins as soon as you’ve invoked it.&amp;#160; For a method that returns a Task, you can think of that Task as representing the eventual asynchronous completion of the method.&amp;#160; But that doesn’t change the fact that invoking the method begins the relevant operation.&amp;#160; Therefore, it would be quite odd if the Task returned from the method was in the Created state, which would mean it represents an operation that hasn’t yet begun.&lt;/p&gt;  &lt;p&gt;So, if you have a public method that returns a Task, and if you create that Task using one of Task’s constructors, make sure you Start the Task before returning it.&amp;#160; Otherwise, you’re likely to cause a deadlock or similar problem in the consuming application, as the consumer will expect the Task to eventually complete when the launched operation completes, and yet if such a Task hasn’t been started, it will never complete.&amp;#160; Some frameworks that allow you to parameterize the framework with methods/delegates that return Tasks even validate the returned Task’s Status, throwing an exception if the Task is still Created.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;8. Question: So, should I use Task’s ctor and Task.Start?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;In the majority of cases, you’re better off using some other mechanism.&amp;#160; For example, if all you want to do is schedule a Task to run some delegate for you, you’re better off using Task.Run or Task.Factory.StartNew, rather than constructing the Task and then Start’ing it; not only will the former methods result in less code, but they’re also cheaper (see question #5 above), and you’re less likely to make a mistake with them, such as forgetting to Start the Task.&lt;/p&gt;  &lt;p&gt;There are of course valid situations in which using the ctor + Start makes sense.&amp;#160; For example, if you choose to derive from Task for some reason, then you’d need to use the Start method to actually queue it.&amp;#160; A more advanced example is if you want the Task to get a reference to itself.&amp;#160; Consider the following (buggy) code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Task theTask = null;     &lt;br /&gt;theTask = Task.Run(() =&amp;gt; Console.WriteLine(“My ID is {0}.”, theTask.Id));&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Spot the flaw?&amp;#160; There’s a race.&amp;#160; During the call to Task.Run, a new Task object is created and is queued to the ThreadPool scheduler.&amp;#160; If there’s not that much going on in the ThreadPool, a thread from the pool might pick it up almost instantly and start running it.&amp;#160; That thread is now racing to access the variable ‘theTask’ with the main thread that called Task.Run and that needs to store the created Task into that ‘theTask’ variable.&amp;#160; I can fix this race by separating the construction and scheduling:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Task theTask = null;     &lt;br /&gt;theTask = new Task(() =&amp;gt;Console.WriteLine(“My ID is {0}.”, theTask.Id));      &lt;br /&gt;theTask.Start(TaskScheduler.Default);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now I’m now sure that the Task instance will have been stored into the ‘theTask’ variable before the ThreadPool processes the Task, because the ThreadPool won’t even get a reference to the Task until Start is called to queue it, and by that point, the reference has already been set (and for those of you familiar with memory models, the appropriate fences are put in place by Task to ensure this is safe).&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10256832" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Awaiting Socket Operations</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx</link><pubDate>Thu, 15 Dec 2011 22:36:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10248293</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10248293</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10248293</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx#comments</comments><description>&lt;p&gt;The System.Net.Sockets.Socket class in .NET exposes multiple sets of asynchronous methods that perform the same basic operations but that are exposed with different patterns.&lt;/p&gt;
&lt;p&gt;The first set follows the APM pattern, where for a synchronous method like Receive, the BeginReceive and EndReceive methods are exposed.&amp;nbsp; If you want to be able to &amp;ldquo;await&amp;rdquo; such asynchronous operations in an async method, the easiest way to do so is to create a Task-based wrapper.&amp;nbsp; That can be done using Task.Factory.FromAsync, or it can be done more manually by using a TaskCompletionSource&amp;lt;TResult&amp;gt;, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;public static Task&amp;lt;int&amp;gt; ReceiveAsync( &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this Socket socket, byte[] buffer, int offset, int size, &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SocketFlags socketFlags) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var tcs = new TaskCompletionSource&amp;lt;int&amp;gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; socket.BeginReceive(buffer, offset, size, socketFlags, iar =&amp;gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try { tcs.TrySetResult(socket.EndReceive(iar)); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; catch (Exception exc) { tcs.TrySetException(exc); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }, null); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return tcs.Task; &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;or with a slightly more efficient implementation that avoids some of the extra allocations here:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;public static Task&amp;lt;int&amp;gt; ReceiveAsync( &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this Socket socket, byte[] buffer, int offset, int size, &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SocketFlags socketFlags) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var tcs = new TaskCompletionSource&amp;lt;int&amp;gt;(socket); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; socket.BeginReceive(buffer, offset, size, socketFlags, iar =&amp;gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var t = (TaskCompletionSource&amp;lt;int&amp;gt;)iar.AsyncState; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var s = (Socket)t.Task.AsyncState; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try { t.TrySetResult(s.EndReceive(iar)); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; catch (Exception exc) { t.TrySetException(exc); } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }, tcs); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return tcs.Task; &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For many asynchronous methods, this approach is good enough.&amp;nbsp; The overhead involved in creating a new TaskCompletionSource&amp;lt;TResult&amp;gt; for each operation is often dwarfed by the costs of the operation itself.&lt;/p&gt;
&lt;p&gt;However, there are some scenarios where this is not sufficient, and not only the additional tasks, but the APM implementation itself.&amp;nbsp; If you&amp;rsquo;re making thousands upon thousands of socket calls asynchronously per second, that&amp;rsquo;s thousands upon thousands of IAsyncResult objects getting created.&amp;nbsp; That&amp;rsquo;s a lot of pressure on the garbage collector, and can result in unacceptable pauses in some networking-intensive apps.&lt;/p&gt;
&lt;p&gt;To address that, Socket exposes another set of asynchronous methods.&amp;nbsp; These methods look similar to the Event-based Async Pattern (EAP), but they&amp;rsquo;re subtly different.&amp;nbsp; Basically, you create a SocketAsyncEventArgs instance, and you configure that instance with a buffer, with a Completion event handler, and so on. Then you pass this instance into methods like ReceiveAsync and&amp;nbsp; SendAsync.&amp;nbsp; Those methods return a Boolean indicating whether they completed synchronously, and if they did, then the event args instance is immediately reusable, and the caller is responsible for finishing the operation synchronously (e.g. checking the status of the operation, getting from the SocketAsyncEventArgs instance the number of bytes received, etc.)&amp;nbsp; If the operation didn&amp;rsquo;t complete synchronously, then the completion event will be raised when it does complete, and that handler does the same completion logic we would have done synchronously.&amp;nbsp; While a bit more complicated, the benefit of this pattern is that these SocketAsyncEventArgs instances can be reused, such that once an instance is no longer being used by a first asynchronous call, it may be reused for a second, and then for a third, and so on.&amp;nbsp; This avoids needing to construct additional objects per async operation, which thereby decreases pressure on the garbage collector.&lt;/p&gt;
&lt;p&gt;We could of course wrap such asynchronous methods with Task, as well, but that would largely defeat the purpose of these methods, similar to allocating an IAsyncResult in the APM case.&amp;nbsp; Still, though, we want to be able to take advantage of the compiler&amp;rsquo;s async/await support to make it easier to write asynchronous code using sockets.&amp;nbsp; We want our cake and to eat it, too.&lt;/p&gt;
&lt;p&gt;Of course, the compiler supports awaiting more than just Tasks.&amp;nbsp; So if you have a specialized scenario like this, you can take advantage of the compiler&amp;rsquo;s pattern-based support for awaiting things.&amp;nbsp; Below, I&amp;rsquo;ve implemented an awaitable wrapper for a SocketAsyncEventArgs:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;public sealed class SocketAwaitable &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private readonly static Action SENTINEL = () =&amp;gt; { };&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; internal bool m_wasCompleted; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; internal Action m_continuation; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; internal SocketAsyncEventArgs m_eventArgs;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public SocketAwaitable(SocketAsyncEventArgs eventArgs) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (eventArgs == null) throw new ArgumentNullException("eventArgs"); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; m_eventArgs = eventArgs; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eventArgs.Completed += delegate &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var prev = m_continuation ?? Interlocked.CompareExchange(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ref m_continuation, SENTINEL, null); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (prev != null) prev(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; internal void Reset() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; m_wasCompleted = false; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; m_continuation = null; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public SocketAwaitable GetAwaiter() { return this; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public bool IsCompleted { get { return m_wasCompleted; } }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void OnCompleted(Action continuation) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (m_continuation == SENTINEL || &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Interlocked.CompareExchange(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ref m_continuation, continuation, null) == SENTINEL) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Task.Run(continuation); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void GetResult() &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (m_eventArgs.SocketError != SocketError.Success) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw new SocketException((int)m_eventArgs.SocketError); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;With that helper type, I can write a short three-line wrapper method for each of the Socket methods I care about, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;public static class SocketExtensions &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static SocketAwaitable ReceiveAsync(this Socket socket, &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SocketAwaitable awaitable) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; awaitable.Reset(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (!socket.ReceiveAsync(awaitable.m_eventArgs)) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; awaitable.m_wasCompleted = true; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return awaitable; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static SocketAwaitable SendAsync(this Socket socket, &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SocketAwaitable awaitable) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; awaitable.Reset(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (!socket.SendAsync(awaitable.m_eventArgs))&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; awaitable.m_wasCompleted = true; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return awaitable; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ... &lt;br /&gt;}&lt;/span&gt; &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;And with that, I can use async/await with these very efficient asynchronous methods on Socket, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;static async Task ReadAsync(Socket s) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Reusable SocketAsyncEventArgs and awaitable wrapper &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var args = new SocketAsyncEventArgs(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; args.SetBuffer(new byte[0x1000], 0, 0x1000); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var awaitable = new SocketAwaitable(args);&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Do processing, continually receiving from the socket &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; while (true) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; await s.ReceiveAsync(awaitable); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int bytesRead = args.BytesTransferred; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (bytesRead &amp;lt;= 0) break;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(bytesRead); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/span&gt; &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here, when I make a call to my ReceiveAsync extension method, I&amp;rsquo;m using a reusable SocketAsyncEventArgs that was previously created and wrapped into one of my helper SocketAwaitable types.&amp;nbsp; ReceiveAsync doesn&amp;rsquo;t need to do any allocation; it simply calls to the underlying ReceiveAsync on the Socket, passing in the wrapped SocketAsyncEventArgs.&amp;nbsp; If the operation completes synchronously, we just set the awaitable&amp;rsquo;s m_wasCompleted to true, such that when the compiler-generated code awaits the returned SocketAwaitable, it sees that IsCompleted is true, and simply proceeds to call GetResult, which will throw an exception if the socket operation failed.&amp;nbsp; If the underlying ReceiveAsync call does not complete synchronously, then m_wasCompleted will remain false, and it&amp;rsquo;ll be up to the OnCompleted method to store the await continuation to be run when the SocketAsyncEventArgs&amp;rsquo; Completed handler is invoked.&amp;nbsp; The only time we need to schedule a task here is if the socket operation asynchronously completes between the time that the compiler-generated code checks IsCompleted and then invokes OnCompleted, and that should be rare.&lt;/p&gt;
&lt;p&gt;If you wanted to write a bit more code, you could even create a specialized version of SocketAwaitable such that its GetResult method returned the result of the operation, e.g. a ReceiveSocketAwaitable whose GetResult method returned the SocketAsyncEventArgs.BytesTransferred value.&amp;nbsp; With that, you could then write the above loop almost as if it were synchronous code, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;static async Task ReadAsync(Socket s) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Reusable SocketAsyncEventArgs and awaitable wrapper &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var args = new SocketAsyncEventArgs(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; args.SetBuffer(new byte[0x1000], 0, 0x1000); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var awaitable = new ReceiveSocketAwaitable(args);&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Do processing, continually receiving from the socket &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int bytesRead; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; while ((bytesRead = await s.ReceiveAsync(awaitable)) &amp;gt; 0) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&lt;/span&gt;&lt;span style="font-family: Consolas;" face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(bytesRead); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Enjoy.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10248293" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Paper :: Guide to Implementing Custom TPL Dataflow Blocks</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/12/05/10244302.aspx</link><pubDate>Mon, 05 Dec 2011 18:14:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10244302</guid><dc:creator>Danny Shih</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10244302</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10244302</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/12/05/10244302.aspx#comments</comments><description>&lt;p&gt;TPL Dataflow includes a number of built-in, already-implemented blocks that target the most common scenarios.&amp;nbsp; Additionally, some flexibility is provided by the set of options that may be used to tweak block behaviors.&amp;nbsp; However, a developer may still choose to implement a custom block for advanced scenarios where the built-in ones are not sufficient.&amp;nbsp; &lt;strong&gt;Zlatko Michailov&lt;/strong&gt; explores the options for achieving this in his paper:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://download.microsoft.com/download/1/6/1/1615555D-287C-4159-8491-8E5644C43CBA/Guide to Implementing Custom TPL Dataflow Blocks.pdf" target="_blank"&gt;Guide to Implementing Custom TPL Dataflow Blocks&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10244302" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Dataflow/">Dataflow</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Coalescing CancellationTokens from Timeouts</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/12/03/10244004.aspx</link><pubDate>Sun, 04 Dec 2011 02:58:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10244004</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10244004</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10244004</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/12/03/10244004.aspx#comments</comments><description>&lt;p&gt;In the .NET Framework 4.5 Developer Preview, you&amp;rsquo;ll find that CancellationTokenSource now has timeout support built directly into its implementation.&amp;nbsp; This makes it very easy to create a token that will automatically have cancellation requested after a particular time interval, e.g.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;" face="Consolas"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken &lt;/span&gt;&lt;/span&gt;FromTimeout(&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;millisecondsDue) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span face="Consolas"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;return new &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationTokenSource&lt;/span&gt;&lt;/span&gt;(millisecondsDue).Token; &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Under the covers here, CancellationTokenSource is creating and configuring a new System.Threading.Timer to call the source&amp;rsquo;s Cancel method after the particular duration passes.&amp;nbsp; The CLR team did some great work for .NET 4.5 to significantly improve the performance of Timer over .NET 4, making this approach not only easy but also well-performing.&amp;nbsp; Of course, there are always scenarios the push the boundaries of performance, and we&amp;rsquo;ve recently seen some high-throughput cases where folks were creating one such CancellationToken for each of thousands upon thousands of asynchronous calls being made per second.&amp;nbsp; That&amp;rsquo;s a lot of Timer and CancellationTokenSource instances.&amp;nbsp; Even with that, the overhead was reasonable, but we&amp;rsquo;re constantly looking for ways to decrease costs.&lt;/p&gt;
&lt;p&gt;One such solution for the consumer is to coalesce tokens.&amp;nbsp; Rather than using a unique CancellationToken per request, we can create one CancellationToken for all timeout requests that will expire at approximately the same time (where we get to configure the size of the span that defines &amp;ldquo;approximately the same time&amp;rdquo;).&amp;nbsp; That way, we can pick how much flexibility we&amp;rsquo;re willing to accept in the timeout (there already needs to be some flexibility anyway given what the OS can guarantee, what other work is on the system consuming cycles, etc.), and trade that off against resource utilization.&amp;nbsp; Here&amp;rsquo;s one way this can be implemented, here using a 50 millisecond coalescing span:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;class&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CoalescedTokens&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;const&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;uint&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; COALESCING_SPAN_MS = 50;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;private&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;readonly&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;ConcurrentDictionary&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;long&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;s_timeToToken = &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;ConcurrentDictionary&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;lt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;long&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;gt;();&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;public&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;static&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; FromTimeout(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; millisecondsTimeout)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; (millisecondsTimeout &amp;lt;= 0)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;return&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;(&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;uint&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; currentTime = (&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;uint&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;Environment&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;.TickCount;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;long&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; targetTime = millisecondsTimeout + currentTime;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;targetTime = ((targetTime + &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;(COALESCING_SPAN_MS - 1)) &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; / COALESCING_SPAN_MS) * COALESCING_SPAN_MS;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; token;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; (!s_timeToToken.TryGetValue(targetTime, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;out&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; token))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;token = &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;new&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationTokenSource&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; (&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;int&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;)(targetTime - currentTime&lt;/span&gt;&lt;/span&gt;).Token;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;if&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; (s_timeToToken.TryAdd(targetTime, token))&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;token.Register(state =&amp;gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;{&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #2b91af;" color="#2b91af"&gt;CancellationToken&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; ignored;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;s_timeToToken.TryRemove((&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;long&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;)state, &lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;out&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; ignored);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}, targetTime);&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier;" size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="mso-spacerun: yes;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #0000ff;" color="#0000ff"&gt;return&lt;/span&gt;&lt;/span&gt;&lt;span style="background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt; token;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" color="#000000"&gt;&lt;span size="2"&gt;&lt;span face="Consolas"&gt;&lt;span style="mso-spacerun: yes;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="margin: 0in 0in 0pt; line-height: normal; list-style-type: disc; mso-layout-grid-align: none;" class="MsoNormal"&gt;&lt;span style="font-family: courier new,courier; background-image: none; background-attachment: scroll; background-repeat: repeat; mso-highlight: white;"&gt;&lt;span style="color: #000000;" face="Consolas" size="2" color="#000000"&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;With that, we can now use CoalescedTokens.FromTimeout to get a CancellationToken that will be canceled within approximately 50 milliseconds of the timeout I requested, such that this same token will be handed out to anyone else asking for a timeout that would expire in the same span.&amp;nbsp; The tokens are all stored in a ConcurrentDictionary, indexed by the time at which the token will have cancellation requested.&amp;nbsp; We first figure out what coalescing interval the incoming request maps to, and look that up in the dictionary.&amp;nbsp; If the token exists, we return it.&amp;nbsp; If it doesn&amp;rsquo;t, we create a new token that will have cancellation requested at the right time, try to add it to the dictionary, and return it.&amp;nbsp; If we were successful at adding it to the dictionary, we also register a cancellation callback that will remove it from the dictionary once cancellation is requested, avoiding a potential leak.&amp;nbsp; Of course, there&amp;rsquo;s a chance there&amp;rsquo;s a race where two requests come in concurrently, don&amp;rsquo;t find an existing token, and each create their own&amp;hellip; and that&amp;rsquo;s fine.&amp;nbsp; It&amp;rsquo;s a &amp;ldquo;benign&amp;rdquo; race, in that each will just get its own token that will expire at the right time, though only one of them will be published for subsequent requestors to use.&lt;/p&gt;
&lt;p&gt;For all but the most intensive of scenarios, if you need a token that will have cancellation requested after some timeout, just do the simple thing of using &amp;ldquo;new CancellationTokenSource(timeout).Token&amp;rdquo; and all should be well.&amp;nbsp; But, if after careful profiling and measurement, you find that this is a bottleneck, hopefully this approach and example can help you to address it&amp;hellip; one more bit of code for your bag of tricks.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10244004" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Cancellation/">Cancellation</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>How to use C++ AMP from C# using WinRT</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/12/10236375.aspx</link><pubDate>Sat, 12 Nov 2011 00:01:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10236375</guid><dc:creator>Igor Ostrovsky - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10236375</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10236375</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/12/10236375.aspx#comments</comments><description>&lt;p&gt;In a previous article, &lt;a title="How to use C++ AMP to C#" href="http://blogs.msdn.com/b/pfxteam/archive/2011/09/21/10214538.aspx"&gt;How to use C++ AMP to C#&lt;/a&gt;, we described how you can use P/Invoke to call into C++ AMP and accelerate your C# apps on GPUs and other heterogeneous hardware. In this post, we'll take a look at how the same task becomes easier in Windows 8 using WinRT.&lt;/p&gt;
&lt;p&gt;Before attempting to call C++ AMP from C#, make sure that you have C++ AMP working on your machine. Daniel Moth&amp;rsquo;s blog post &lt;a title="VS 11 Developer Preview gotchas with C++ AMP" href="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/09/19/vs-11-developer-preview-gotchas-with-c-amp.aspx"&gt;VS 11 Developer Preview gotchas with C++ AMP&lt;/a&gt; explains how to get that done.&lt;/p&gt;
&lt;h2&gt;The short story&lt;/h2&gt;
&lt;p&gt;Once you have C++ AMP working on your machine, the easiest way to start using it from C# via WinRT is to open &lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-23-63-75/HelloWorldCSharpWinRT.ZIP"&gt;this sample project&lt;/a&gt; in Visual Studio 11 and begin experimenting with the code.&lt;/p&gt;
&lt;h2&gt;The long story&lt;/h2&gt;
&lt;p&gt;If you have an existing Metro style app that you&amp;rsquo;d like to modify to use C++ AMP &amp;ndash; or you&amp;rsquo;d like to understand how the sample is set up &amp;ndash; you can follow the steps below. In summary, you need to take the following steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Step 1: Open or create a C# Metro style project in Visual Studio 11&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Choose the platform target as X86 (if you plan to write 32-bit C++ AMP code).&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Step 2: Create a C++ WinRT Component DLL project&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;DO NOT build the project before completing step 3&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Step 3: Add the C++ project as a reference to the C# project.&lt;/li&gt;
&lt;li&gt;Step 4: Write the C++ AMP and the C# code&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Step 1: Open or create a&amp;nbsp;C# Metro style&amp;nbsp;project&lt;/h3&gt;
&lt;p&gt;First, you need to open or create a C# Metro style application project. The rest of the article assumes that the project is named HelloWorldCSharpWinRT:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/7711.image1.png"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/7711.image1.png" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Also, set the "Platform target" of the project to "X86".&lt;/p&gt;
&lt;h3&gt;Step 2: Create a C++ WinRT Component DLL project&lt;/h3&gt;
&lt;p&gt;Now, you can add a Visual C++ WinRT component&amp;nbsp; that will contain the C++ AMP code. Simply create a project named "HelloWorldLib" from the "WinRT Component DLL" template:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/7288.image2.png"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/7288.image2.png" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;span style="color: #ff0000;"&gt;WARNING:&lt;/span&gt;&lt;/strong&gt; Do not build the project yet! Due to a bug in the Visual Studio 11 Developer Preview, building the project before completing step 3 will cause problems, and you may be stuck having to delete and&amp;nbsp;recreate the C++ WinRT&amp;nbsp;project.&lt;/p&gt;
&lt;h3&gt;Step 3: Add reference from HelloWorldCSharpWinRT to HelloWorldLib&lt;/h3&gt;
&lt;p&gt;With WinRT, you can simply add HelloWorldLib as a reference to HelloWorldCSharpWinRT. No more manual editing of the csproj file is necessary, as it was with P/Invoke! Just right-click HelloWorldCSharpWinRT, choose "Add Reference..." and select the HelloWorldLib project:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/2287.image3.png"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73/2287.image3.png" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Step 4. Write the C++ AMP and the C# code&lt;/h3&gt;
&lt;p&gt;Now, we just need to write the C++ AMP code and call it from C#.&lt;/p&gt;
&lt;p&gt;Since a C++ AMP kernel may take a long time to execute, the WinRT guidelines state that the kernel should be exposed as an asynchronous operation. A convenient way to expose asynchronous operations in C++ is via create_async, currently available in the&amp;nbsp;&lt;a href="http://code.msdn.microsoft.com/windowsapps/Windows-8-Asynchronous-08009a0d"&gt;PPL Sample Pack&lt;/a&gt;&amp;nbsp;(for details on how this works, see &lt;a href="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/10/27/try-it-now-use-ppl-to-produce-windows-8-asynchronous-operations.aspx"&gt;Try It Now: Use PPL to Produce Windows 8 Asynchronous Operations&lt;/a&gt;)&lt;span size="3"&gt;&lt;span lang=""&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Extract ppltasks.preview.h from the sample pack and include it as a header file in HelloWorldCSharpWinRT.&lt;/p&gt;
&lt;p&gt;Delete WinRTComponent.h.&lt;/p&gt;
&lt;p&gt;Modify WinRTComponent.cpp as follows:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;"&gt;#include "amp.h"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;#include "ppltasks.preview.h"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;#include "collection.h"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;#include &amp;lt;vector&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using namespace concurrency;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using namespace Windows::Foundation;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using namespace Windows::Foundation::Collections;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;namespace HelloWorldLib&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;{&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public ref class WinRTComponent sealed&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public:&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IAsyncOperation&amp;lt;IVectorView&amp;lt;float&amp;gt;^&amp;gt;^ square_array_async(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IVectorView&amp;lt;float&amp;gt;^ input)&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Synchronously copy input data from host to device&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int size = input-&amp;gt;Size;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;array&amp;lt;float, 1&amp;gt; *dataPt = new array&amp;lt;float, 1&amp;gt;(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; size, begin(input), end(input));&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;// Asynchronously perform the computation on the GPU&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return preview::create_async( [=]() -&amp;gt; IVectorView&amp;lt;float&amp;gt;^&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Run the kernel on the GPU&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; parallel_for_each(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataPt-&amp;gt;grid, [=] (index&amp;lt;1&amp;gt; idx) mutable restrict(direct3d)&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; (*dataPt)[idx] = (*dataPt)[idx] * (*dataPt)[idx];&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Copy outputs from device to host&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;std::vector&amp;lt;float&amp;gt; vec = std::vector&amp;lt;float&amp;gt;(size);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; copy((*dataPt), vec.begin());&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; delete dataPt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Return the outputs as a VectorView&amp;lt;float&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return ref new Platform::VectorView&amp;lt;float&amp;gt;(vec);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Notice that the square-array operation is exposed via an asynchronous API. In WinRT, operations that may be long-running should be exposed via asynchronous APIs, and GPU operations may take a relatively long time to execute.&lt;/p&gt;
&lt;p&gt;That is all that we need on the C++ side. Now, we'll add a button to the C# project. Modify MainPage.xaml as follows:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;lt;UserControl x:Class="HelloWorldCSharpWinRT.MainPage"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; mc:Ignorable="d"&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; d:DesignHeight="768" d:DesignWidth="1366"&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Grid x:Name="LayoutRoot" Background="#FF0C0C0C"&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Button x:Name="Button_Example" Content="Click"&amp;nbsp; Click="Button_Example_Click" HorizontalAlignment="Center"/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/Grid&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;lt;/UserControl&amp;gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;When the user clicks the button, we'll call into C++ AMP. Modify MainPage.xaml.cs as follows:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: courier new,courier;"&gt;using System;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using System.Collections.Generic;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using Windows.UI.Popups;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using Windows.UI.Xaml;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;using HelloWorldLib;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;&lt;br /&gt;namespace HelloWorldCSharpWinRT&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;{&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; partial class MainPage&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public MainPage()&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; InitializeComponent();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pr&lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;ivate async void Button_Example_Click(&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; object sender, RoutedEventArgs e)&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Button_Example.IsEnabled = false;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var arr = new [] { 1.0f, 2.0f, 3.0f, 4.0f };&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; List&amp;lt;float&amp;gt; inputs = new List&amp;lt;float&amp;gt;(arr);&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;IReadOnlyList&amp;lt;float&amp;gt; outputs =&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;await new WinRTComponent()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .square_array_async(inputs);&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="font-family: courier new,courier;"&gt;await new MessageDialog(string.Join(",", outputs)).ShowAsync();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Button_Example.IsEnabled = true;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new,courier;"&gt;}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&amp;hellip; and that&amp;rsquo;s it!&lt;/p&gt;
&lt;p&gt;Note that this is a very simple example that demonstrates how to call a C++ AMP function from C#. The example is too na&amp;iuml;ve to demonstrate speedup &amp;ndash; it contains too little work per data element and in total to benefit from GPU acceleration. An example of a workload that does demonstrate speedup is matrix multiplication, and here is a link to &lt;a href="http://www.danielmoth.com/Blog/Matrix-Multiplication-With-C-AMP.aspx"&gt;C++ AMP code for Matrix Multiplication&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10236375" width="1" height="1"&gt;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-23-63-75/HelloWorldCSharpWinRT.ZIP" length="85958" type="application/zip" /></item><item><title>New in .NET 4.5: ThreadLocal.Values</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10236000.aspx</link><pubDate>Fri, 11 Nov 2011 01:12:50 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10236000</guid><dc:creator>Igor Ostrovsky - MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10236000</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10236000</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10236000.aspx#comments</comments><description>&lt;p&gt;Available since .NET 4, ThreadLocal&amp;lt;T&amp;gt; is a container that holds a separate value for every thread. In practice, ThreadLocal&amp;lt;T&amp;gt; is often convenient for storing per-thread counters, resources, or partial results.&lt;/p&gt;  &lt;p&gt;As mentioned &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2010/10/21/10079121.aspx"&gt;earlier&lt;/a&gt; on this blog, we have been thinking about adding a Values property to enumerate over the values from &lt;b&gt;all&lt;/b&gt; threads that ever stored a value into the ThreadLocal&amp;lt;T&amp;gt; instance. After getting helpful feedback from this blog and other sources, we ended up implementing the capability in .NET 4.5.&lt;/p&gt;  &lt;p&gt;To use the Values property, you have to initialize the ThreadLocal&amp;lt;T&amp;gt; instance by setting the constructor argument trackAllValues= true. The sample below demonstrates this usage:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;var localResult = &lt;span class="kwrd"&gt;new&lt;/span&gt; ThreadLocal&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;(() =&amp;gt; 0, trackAllValues: &lt;span class="kwrd"&gt;true&lt;/span&gt;);
Parallel.For(0, 10000, i =&amp;gt;
{
    localResult.Value += Compute(i);
});

&lt;span class="kwrd"&gt;int&lt;/span&gt; result = localResult.Values.Sum();&lt;/pre&gt;


&lt;h3&gt;Explicit Opt-In&lt;/h3&gt;

&lt;p&gt;If you don’t set the trackAllValues constructor argument to true, accessing the Values property will throw an InvalidOperationException. The Values property requires additional bookkeeping, and so ThreadLocal&amp;lt;T&amp;gt; requires that you declare upfront if you plan to access Values.&lt;/p&gt;

&lt;p&gt;Most importantly, trackAllValues=true changes the lifetime of the values stored into a ThreadLocal&amp;lt;T&amp;gt;. By default (i.e., trackAllValues=false), a value stored into a ThreadLocal&amp;lt;T&amp;gt; is cleared when the ThreadLocal&amp;lt;T&amp;gt; instance is disposed/finalized OR when the corresponding thread exits, whichever happens first. This is the same behavior that ThreadLocal&amp;lt;T&amp;gt; had in .NET 4, and can be especially important when T is a large reference type.&lt;/p&gt;

&lt;p&gt;However, removing a value when its corresponding thread exits would make the Values property poorly behaved. For example, in the code sample shown earlier in this blog post, the final summation should clearly process &lt;b&gt;all&lt;/b&gt; partial results. It would be unacceptable to omit one of the partial results, say because the ThreadPool has decided to retire the thread that computed it.&lt;/p&gt;

&lt;p&gt;So, if you set trackAllValues=true, the ThreadLocal instance will keep track of all values that have been stored into it, even if the corresponding threads are now gone. Then, the values can be returned via the Values property.&lt;/p&gt;

&lt;h3&gt;More Scenarios&lt;/h3&gt;

&lt;p&gt;In addition to aggregation of partial results, the Values property can be useful for resource cleanup. The example below executes a Parallel.For loop, where each thread participating in the loop opens its own connection to the database. Once the loop completes, we can use the Values property to release all connections that have been opened:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var threadDbConn = &lt;span class="kwrd"&gt;new&lt;/span&gt; ThreadLocal&amp;lt;MyDbConnection&amp;gt;(() =&amp;gt; MyDbConnection.Open(), &lt;span class="kwrd"&gt;true&lt;/span&gt;);
&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    Parallel.For(0, 10000, i =&amp;gt;
    {
        var inputData = threadDbConn.Value.GetData(i);
        ...
    });
}
&lt;span class="kwrd"&gt;finally&lt;/span&gt;
{
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt;(var dbConn &lt;span class="kwrd"&gt;in&lt;/span&gt; threadDbConn.Values)
    {
        dbConn.Close();
    }
}&lt;/pre&gt;


&lt;p&gt;Additionally, readers of this blog suggested in comments that the Values property would be useful to simplify existing parallel loops, to aggregate data parallel code that does not use parallel loops, to implement an optimized object pool, and to gather high-performance statistics.&lt;/p&gt;

&lt;p&gt;If you find this new property useful in your code, please let us know in the comments!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10236000" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Coordination+Data+Structures/">Coordination Data Structures</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>PLINQ Queries That Run in Parallel in .NET 4.5</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10235999.aspx</link><pubDate>Fri, 11 Nov 2011 01:12:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235999</guid><dc:creator>Igor Ostrovsky - MSFT</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10235999</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10235999</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10235999.aspx#comments</comments><description>&lt;p&gt;One interesting thing to know about PLINQ is that not all queries are guaranteed to execute in parallel (See &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2009/10/31/9915569.aspx"&gt;PLINQ Queries That Run Sequentially&lt;/a&gt; for reference). You can think of the AsParallel method as a hint to run in parallel for query shapes that it believes will be faster. By default, PLINQ prefers to use a simple sequential algorithm over a potentially expensive parallel algorithm, and so some queries will execute sequentially, especially queries where the chain of operators do not lend themselves to parallelism. The bottom line is that PLINQ’s intent is to run your queries as fast as possible, so if there’s a good likelihood that the complexities of parallelism will slow it down, PLINQ will perform the query sequentially rather than in parallel.&lt;/p&gt;  &lt;p&gt;In .NET 4.5, PLINQ’s algorithms have improved over .NET 4 such that its set of parallelizable queries has broadened and substantially fewer queries fall back to sequential execution. For example, the following query would execute sequentially in .NET 4 but now executes in parallel in .NET 4.5:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;intArray.AsParallel()
    .Select(x =&amp;gt; Foo(x))
    .TakeWhile(x =&amp;gt; Filter(x))
    .ToArray();&lt;/pre&gt;


&lt;p&gt;Since the query executes sequentially in .NET 4, the query would not get any speedup even if the Foo() method is expensive. For some cases, the choice to fallback to a sequential implementation might be too conservative, and as a developer you might choose to override it. In order to force PLINQ to use a parallel algorithm in .NET 4, the user can call the WithExecutionMode operator:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;intArray.AsParallel()
    .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
    .Select(x =&amp;gt; Foo(x))
    .TakeWhile(x =&amp;gt; Filter(x))
    .ToArray();&lt;/pre&gt;


&lt;p&gt;In .NET 4.5, the behavior of the TakeWhile operator has changed, and so the query executes in parallel even without the WithExecutionMode hint.&lt;/p&gt;

&lt;h3&gt;Sequential Fallback in .NET 4 and .NET 4.5&lt;/h3&gt;

&lt;p&gt;One way to illustrate the improvements to the sequential fallback is to look at the list of operators that may cause the query to fallback to sequential. Whether or not the operator actually causes a sequential fallback depends on other operators in the query as well. &lt;/p&gt;

&lt;p&gt;Operators that may cause sequential fallback in both .NET 4 and .NET 4.5 are marked in &lt;b&gt;&lt;font style="background-color: rgb(79, 129, 189);"&gt;blue&lt;/font&gt;&lt;/b&gt;, and operators that may cause fallback in .NET 4 but no longer in .NET 4.5 are marked in &lt;b&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;orange&lt;/font&gt;&lt;/b&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73-metablogapi/3716.image_5F00_44074AA3.png"&gt;&lt;img style="border: 0px currentcolor; display: inline; background-image: none;" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-88-73-metablogapi/8510.image_5F00_thumb_5F00_7CB1F4B0.png" width="550" height="238" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, in .NET 4.5, as long as the query does not contain positional operators or the ElementAt operator, it will not fall back to sequential. &lt;/p&gt;

&lt;p&gt;The positional operators mentioned above are the operator overloads that pass the position of each element into the user delegate. So, while the ‘ordinary’ Select operator accepts a delegate of type Func&amp;lt;TInput, TOutput&amp;gt;, the positional Select accepts a delegate of type Func&amp;lt;TInput, &lt;b&gt;int,&lt;/b&gt; TOutput&amp;gt;. The position of each element is passed into the delegate as the input second parameter.&lt;/p&gt;

&lt;p&gt;The ForceParallelism execution mode is still available for those items called out above.&lt;/p&gt;

&lt;h3&gt;Potential Risks of the Change&lt;/h3&gt;

&lt;p&gt;The fact that some queries used to execute sequentially and now execute in parallel opens up the possibility of exposing more latent race conditions in users’ code.&lt;/p&gt;

&lt;p&gt;Here is an example of a query that happens to work in .NET 4, but will not work in .NET 4.5:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;List&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; list = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
var q = src.AsParallel()
    .Select(x =&amp;gt; { list.Add(x); &lt;span class="kwrd"&gt;return&lt;/span&gt; x; })
    .Where(x =&amp;gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;)
    .Take(100);&lt;/pre&gt;


&lt;p&gt;There is a bug in the query above: the delegate passed into the Select operator is not thread-safe. However, the query will still happen to work in .NET 4, because as an implementation detail PLINQ decides to execute the query sequentially. In .NET 4.5, the query will run in parallel, and so list.Add(x) could be called from multiple threads concurrently, potentially resulting in a corrupted List&amp;lt;T&amp;gt; instance. &lt;/p&gt;

&lt;p&gt;However, the idea that user delegates may be called from multiple cores is a core premise of PLINQ, so hopefully no user code in the real world will be broken by the change.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Related Resources:&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2009/10/31/9915569.aspx"&gt;PLINQ Queries That Run Sequentially&lt;/a&gt;

  &lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelexecutionmode.aspx"&gt;MSDN Documentation for ParallelExecutionMode Enumeration&lt;/a&gt;

  &lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd547138.aspx"&gt;How to: Specify the Execution Mode in PLINQ&lt;/a&gt;

  &lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd997399.aspx"&gt;Understanding Speedup in PLINQ&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235999" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/PLINQ/">PLINQ</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Paper :: TPL Performance Improvements in .NET 4.5</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235962.aspx</link><pubDate>Thu, 10 Nov 2011 22:39:25 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235962</guid><dc:creator>Danny Shih</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10235962</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10235962</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235962.aspx#comments</comments><description>&lt;p&gt;We invested a lot of time into making parallel programming “just faster” for .NET 4.5.&amp;#160; You’ve already seen some &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2011/11/08/10235147.aspx"&gt;neat tricks to ConcurrentDictionary&lt;/a&gt;.&amp;#160; There’s a lot more to say about improving the performance of the Task Parallel Library, and&lt;strong&gt; Joe Hoag&lt;/strong&gt; has a written an excellent paper on the subject:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://download.microsoft.com/download/1/6/1/1615555D-287C-4159-8491-8E5644C43CBA/TPL Performance Improvements in .Net 4.5.pdf" target="_blank"&gt;TPL Performance Improvements in .NET 4.5&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The paper examines some of the changes made to TPL in .NET 4.5, compares times for selected operations in .NET 4 vs .NET 4.5, and makes some general “best practices” recommendations for those interested in using TPL performantly in .NET 4.5.&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235962" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Crafting a Task.TimeoutAfter Method</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx</link><pubDate>Thu, 10 Nov 2011 15:50:11 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235834</guid><dc:creator>Joe Hoag</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10235834</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10235834</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx#comments</comments><description>&lt;p&gt;Imagine that you have a Task handed to you by a third party, and that you would like to force this Task to complete within a specified time period. However, you cannot alter the “natural” completion path and completion state of the Task, as that may cause problems with other consumers of the Task. So you need a way to obtain a copy or “proxy” of the Task that will either (A) complete within the specified time period, or (B) will complete with an indication that it had timed out.&lt;/p&gt;  &lt;p&gt;In this blog post, I will show how one might go about implementing a Task.TimeoutAfter method to support this scenario. The signature of TimeoutAfter would look like this:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task TimeoutAfter(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task task, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)&lt;/pre&gt;


&lt;p&gt;The returned &lt;i&gt;proxy&lt;/i&gt; Task can complete in one of two ways:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If task completes before the specified timeout period has elapsed, then the proxy Task finishes when task finishes, with task’s completion status being copied to the proxy.&lt;/li&gt;

  &lt;li&gt;If task fails to complete before the specified timeout period has elapsed, then the proxy Task finishes when the timeout period expires, in Faulted state with a TimeoutException.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In addition to showing how to implement Task.TimeoutAfter, this post will also shed some light on the general thought process that should go into implementing such a feature.&lt;/p&gt;

&lt;h3&gt;A First Try&lt;/h3&gt;

&lt;p&gt;Here’s some code that will do the trick:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; VoidTypeStruct { }  &lt;span class="rem"&gt;// See Footnote #1&lt;/span&gt;

&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; TaskExtensions
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task TimeoutAfter(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task task, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)
    {
        &lt;span class="rem"&gt;// tcs.Task will be returned as a proxy to the caller&lt;/span&gt;
        TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt; tcs = 
            &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;();

        &lt;span class="rem"&gt;// Set up a timer to complete after the specified timeout period&lt;/span&gt;
        Timer timer = &lt;span class="kwrd"&gt;new&lt;/span&gt; Timer(_ =&amp;gt; 
        {
            &lt;span class="rem"&gt;// Fault our proxy Task with a TimeoutException&lt;/span&gt;
            tcs.TrySetException(&lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException()); 
        }, &lt;span class="kwrd"&gt;null&lt;/span&gt;, millisecondsTimeout, Timeout.Infinite);

        &lt;span class="rem"&gt;// Wire up the logic for what happens when source task completes&lt;/span&gt;
        task.ContinueWith(antecedent =&amp;gt;
        {
            timer.Dispose(); &lt;span class="rem"&gt;// Cancel the timer&lt;/span&gt;
            MarshalTaskResults(antecedent, tcs); &lt;span class="rem"&gt;// Marshal results to proxy&lt;/span&gt;
        }, CancellationToken.None, 
            TaskContinuationOptions.ExecuteSynchronously, 
            TaskScheduler.Default);

        &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;
    }
}&lt;/pre&gt;


&lt;p&gt;Simple enough, right? You start a Timer job that faults the proxy Task, and also add a continuation off of the source Task that transfers the completion state of the source to the proxy. The final state of the proxy will therefore depend on which completes first, the Timer job or the source Task.&lt;/p&gt;

&lt;p&gt;And by the way, MarshalTaskResults is implemented like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; MarshalTaskResults&amp;lt;TResult&amp;gt;(
    Task source, TaskCompletionSource&amp;lt;TResult&amp;gt; proxy)
{
    &lt;span class="kwrd"&gt;switch&lt;/span&gt; (source.Status)
    {
        &lt;span class="kwrd"&gt;case&lt;/span&gt; TaskStatus.Faulted:
            proxy.TrySetException(source.Exception);
            &lt;span class="kwrd"&gt;break&lt;/span&gt;;
        &lt;span class="kwrd"&gt;case&lt;/span&gt; TaskStatus.Canceled:
            proxy.TrySetCanceled();
            &lt;span class="kwrd"&gt;break&lt;/span&gt;;
        &lt;span class="kwrd"&gt;case&lt;/span&gt; TaskStatus.RanToCompletion:
            Task&amp;lt;TResult&amp;gt; castedSource = source &lt;span class="kwrd"&gt;as&lt;/span&gt; Task&amp;lt;TResult&amp;gt;;
            proxy.TrySetResult(
                castedSource == &lt;span class="kwrd"&gt;null&lt;/span&gt; ? &lt;span class="kwrd"&gt;default&lt;/span&gt;(TResult) : &lt;span class="rem"&gt;// source is a Task&lt;/span&gt;
                    castedSource.Result); &lt;span class="rem"&gt;// source is a Task&amp;lt;TResult&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;break&lt;/span&gt;;
    }
}&lt;/pre&gt;


&lt;p&gt;The “RanToCompletion” handling might seem a little more complicated than it needs to be, but it will allow us to handle Task&amp;lt;TResult&amp;gt; objects correctly (discussed briefly below).&lt;/p&gt;

&lt;h3&gt;Can We Do Better?&lt;/h3&gt;

&lt;p&gt;While our first stab at a TimeoutAfter method is functionally correct, we could streamline it and improve its performance. Specifically, notice that our Timer and continuation delegates “capture” variables; this will cause the compiler to allocate special “closure” classes for these delegates behind the scenes, which will slow down our method. To eliminate the need for the closure class allocations, we can pass all “captured” variables in through state variables for those respective calls, like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task TimeoutAfter(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task task, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)
{
    &lt;span class="rem"&gt;// tcs.Task will be returned as a proxy to the caller&lt;/span&gt;
    TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt; tcs = 
        &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;();

    &lt;span class="rem"&gt;// Set up a timer to complete after the specified timeout period&lt;/span&gt;
    Timer timer = &lt;span class="kwrd"&gt;new&lt;/span&gt; Timer(state =&amp;gt; 
    { 
&lt;font style=""&gt;        &lt;/font&gt;&lt;font style=""&gt;&lt;span class="rem"&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;// Recover our state data&lt;/font&gt;&lt;/span&gt;
        &lt;font style="background-color: rgb(243, 164, 71);"&gt;var myTcs = (TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;)state;&lt;/font&gt;&lt;/font&gt;
&lt;br /&gt;        &lt;span class="rem"&gt;// Fault our proxy Task with a TimeoutException&lt;/span&gt;
        myTcs.TrySetException(&lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException()); 
    }, &lt;font style="background-color: rgb(243, 164, 71);"&gt;tcs&lt;/font&gt;, millisecondsTimeout, Timeout.Infinite);

    &lt;span class="rem"&gt;// Wire up the logic for what happens when source task completes&lt;/span&gt;
    task.ContinueWith((antecedent,state) =&amp;gt;
    {
&lt;font style=""&gt;&lt;/font&gt;&lt;font style=""&gt;        &lt;span class="rem"&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;// Recover our state data&lt;/font&gt;&lt;/span&gt;
        &lt;/font&gt;&lt;font style=""&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;var tuple = &lt;br /&gt;&lt;/font&gt;        &lt;font style="background-color: rgb(243, 164, 71);"&gt;    (Tuple&amp;lt;Timer, TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;&amp;gt;)state;&lt;/font&gt;&lt;/font&gt;

        &lt;span class="rem"&gt;// Cancel the timer&lt;/span&gt;
        tuple.Item1.Dispose();&lt;br /&gt;        &lt;span class="rem"&gt;// Marshal results to proxy&lt;/span&gt;&lt;br /&gt;        MarshalTaskResults(antecedent, tuple.Item2);    &lt;br /&gt;    }, &lt;br /&gt;&lt;font style=""&gt;    &lt;/font&gt;&lt;font style=""&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;Tuple.Create(timer,tcs),  &lt;span class="rem"&gt;// See Footnote #2&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;
    CancellationToken.None,
    TaskContinuationOptions.ExecuteSynchronously,
    TaskScheduler.Default);

    &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;
}&lt;/pre&gt;


&lt;p&gt;Some ad-hoc performance tests show that this little optimization shaves about 12% off of the overhead from the TimeoutAfter method.&lt;/p&gt;

&lt;h3&gt;What about Edge Cases?&lt;/h3&gt;

&lt;p&gt;What do we do when the caller specifies a zero timeout, or an infinite timeout? What if the source Task has already completed by the time that we enter the TimeoutAfter method? We can address these edge cases in the TimeoutAfter implementation as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task TimeoutAfter(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task task, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)
{
&lt;font style=""&gt;&lt;/font&gt;&lt;font style=""&gt;    &lt;span class="rem"&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;// Short-circuit #1: infinite timeout or task already completed&lt;/font&gt;&lt;/span&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (task.IsCompleted || (millisecondsTimeout == Timeout.Infinite))&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;{&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    &lt;span class="rem"&gt;// Either the task has already completed or timeout will never occur.&lt;/span&gt;&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    &lt;span class="rem"&gt;// No proxy necessary.&lt;/span&gt;&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; task;&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;}&lt;/font&gt;&lt;/font&gt;

    &lt;span class="rem"&gt;// tcs.Task will be returned as a proxy to the caller&lt;/span&gt;
    TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt; tcs = 
        &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;();

&lt;font style=""&gt;&lt;/font&gt;&lt;font style=""&gt;    &lt;span class="rem"&gt;&lt;font style="background-color: rgb(243, 164, 71);"&gt;// Short-circuit #2: zero timeout&lt;/font&gt;&lt;/span&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (millisecondsTimeout == 0)&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;{&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    &lt;span class="rem"&gt;// We've already timed out.&lt;/span&gt;&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    tcs.SetException(&lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException());&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;&lt;/font&gt;
    &lt;font style="background-color: rgb(243, 164, 71);"&gt;}&lt;/font&gt;&lt;/font&gt;

    &lt;span class="rem"&gt;// Set up a timer to complete after the specified timeout period&lt;/span&gt;
    Timer timer = &lt;span class="kwrd"&gt;new&lt;/span&gt; Timer(state =&amp;gt; 
    {
        &lt;span class="rem"&gt;// Recover your state information&lt;/span&gt;
        var myTcs = (TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;)state;

        &lt;span class="rem"&gt;// Fault our proxy with a TimeoutException&lt;/span&gt;
        myTcs.TrySetException(&lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException()); 
    }, tcs, millisecondsTimeout, Timeout.Infinite);

    &lt;span class="rem"&gt;// Wire up the logic for what happens when source task completes&lt;/span&gt;
    task.ContinueWith((antecedent, state) =&amp;gt;
    {
        &lt;span class="rem"&gt;// Recover our state data&lt;/span&gt;
        var tuple = 
            (Tuple&amp;lt;Timer, TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;&amp;gt;)state;

        &lt;span class="rem"&gt;// Cancel the Timer&lt;/span&gt;
        tuple.Item1.Dispose();

        &lt;span class="rem"&gt;// Marshal results to proxy&lt;/span&gt;
        MarshalTaskResults(antecedent, tuple.Item2);
    }, 
    Tuple.Create(timer, tcs),
    CancellationToken.None,
    TaskContinuationOptions.ExecuteSynchronously,
    TaskScheduler.Default);

    &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;
}&lt;/pre&gt;


&lt;p&gt;Such changes ensure efficient handling of the edge cases associated with TimeoutAfter.&lt;/p&gt;

&lt;h3&gt;A Different Approach&lt;/h3&gt;

&lt;p&gt;My colleague Stephen Toub informed me of another potential implementation of Task.TimeoutAfter:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; async Task TimeoutAfter(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task task, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)
{
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (task == &lt;font color="#0000ff"&gt;await&lt;/font&gt; Task.WhenAny(task, Task.Delay(millisecondsTimeout))) 
        &lt;font color="#0000ff"&gt;await&lt;/font&gt; task;
    &lt;span class="kwrd"&gt;else&lt;/span&gt;
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException();
}&lt;/pre&gt;


&lt;p&gt;The implementation above takes advantage of the new async/await support in .NET 4.5, and is pleasingly concise. However, it does lack some optimizations:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The edge cases described previously are not handled well. (But that could probably be fixed.)&lt;/li&gt;

  &lt;li&gt;A Task is created via Task.Delay, instead of just a simple timer job.&lt;/li&gt;

  &lt;li&gt;In the cases where the source Task (task) completes before the timeout expires, no effort is made to cancel the internal timer job that was launched in the Task.Delay call. If the number of “zombie” timer jobs starts becoming significant, performance could suffer.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nevertheless, it is good to consider the use of async/await support in implementing features like this. Often await will be optimized in ways that simple continuations are not.&lt;/p&gt;

&lt;h3&gt;What about TimeoutAfter&amp;lt;TResult&amp;gt;?&lt;/h3&gt;

&lt;p&gt;Suppose that we want to implement the generic version of TimeoutAfter?&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task TimeoutAfter&amp;lt;TResult&amp;gt;(
    &lt;span class="kwrd"&gt;this&lt;/span&gt; Task&amp;lt;TResult&amp;gt; task, 
    &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout)
&lt;/pre&gt;


&lt;p&gt;It turns out that the implementation of the above would be nearly identical to the non-generic version, except that a TaskCompletionSource&amp;lt;TResult&amp;gt; would be used instead of a TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;. The MarshalTaskResults method was already written to correctly handle the marshaling of the results of generic Tasks.&lt;/p&gt;

&lt;hr align="left" size="1" width="33%" /&gt;

&lt;p&gt;[1] There is no non-generic version of TaskCompletionSource&amp;lt;TResult&amp;gt;. So, if you want a completion source for a Task (as opposed to a Task&amp;lt;TResult&amp;gt;), you still need to provide some throwaway TResult type to TaskCompletionSource. For this example, we’ve created a dummy type (VoidTypeStruct), and we create a TaskCompletionSource&amp;lt;VoidTypeStruct&amp;gt;.&lt;/p&gt;

&lt;p&gt;[2] So does it really buy you anything to replace a closure allocation with a tuple allocation? The answer is “yes”. If you were to examine the IL produced from the original code, you would see that both a closure object and a delegate need to be allocated for this call. Eliminating variable capture in the delegate typically allows the compiler to cache the delegate, so in effect two allocations are saved by eliminating variable capture. Thus in this code we’ve traded closure and delegate allocations for a Tuple allocation, so we still come out ahead. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235834" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Exception Handling in TPL Dataflow Networks</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235570.aspx</link><pubDate>Thu, 10 Nov 2011 00:03:31 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235570</guid><dc:creator>Cristina Manu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10235570</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10235570</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235570.aspx#comments</comments><description>&lt;p&gt;A “dataflow block” is represented by a class implementing the IDataflowBlock interface. The state of a dataflow block is represented by the state of its IDataflowBlock.Completion Task, which itself has a Status property. When a dataflow block is in active state, meaning that it is currently doing processing or may do more processing in the future, its Completion task will be in a non-final state, such as TaskStatus.WaitingForActivation. Once the dataflow block has completed all of its processing, either successfully or due to failure or cancellation, the Completion task’s Status will return one of the three values below:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;RanToCompletion&lt;/li&gt;    &lt;li&gt;Canceled&lt;/li&gt;    &lt;li&gt;Faulted&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This blog post will focus on the third state of a completed dataflow block: Faulted.&lt;/p&gt;  &lt;p&gt;Current users of the Task Parallel Library (TPL) will notice that the exception model employed by TPL Dataflow follows the same model as TPL. In TPL, if an exception goes unhandled in a Task’s delegate, the Task ends in the Faulted state. Following the same model, in TPL Dataflow if an exception goes unhandled during the processing of a message, the exception will fault the block’s Completion task. The Exception will be available from the block’s Completion Task’s Exception property, and it can be handled as in TPL model. Note, as well, that execution blocks (e.g. ActionBlock) may support parallel processing, such that the block can be processing multiple messages concurrently; this can be configured via the MaxDegreeOfParallelism property on the DataflowBlockOptions used to configure the block when it is constructed. As with parallel loops and PLINQ queries, exceptions in such parallel processing do not forcibly interrupt other concurrent processing, nor is the construct’s processing considered completed the moment the exception occurs; if an exception does occur, the dataflow block will complete only once all processing has quiesced.&lt;/p&gt;  &lt;h3&gt;Transition to “Faulted” state&lt;/h3&gt;  &lt;p&gt;If one of the below conditions is met the block will move to Faulted state.&lt;/p&gt;  &lt;p&gt;1. &lt;b&gt;&lt;i&gt;Explicit Fault&lt;/i&gt;&lt;/b&gt;: The invocation of IDataflowBlock.Fault(Exception) will Fault the block. In this case, the exception provided as an argument to the Fault method will be used as the block’s Completion Task’s exception. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; block = &lt;span class="kwrd"&gt;new&lt;/span&gt; BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();

((IDataflowBlock)block).Fault(&lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;&amp;quot;Test&amp;quot;&lt;/span&gt;));&lt;/pre&gt;


&lt;p&gt;2. &lt;b&gt;&lt;i&gt;Unhandled Delegate Exception&lt;/i&gt;&lt;/b&gt;: For blocks that run user delegates, e.g. ActionBlock, the user-provided delegate could throw exceptions. Any unhandled exception from these delegates will fault the block. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;ActionBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; action = &lt;span class="kwrd"&gt;new&lt;/span&gt; ActionBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;((x) =&amp;gt; 
{ 
    &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;&amp;quot;Test&amp;quot;&lt;/span&gt;); 
});

action.Post(1);

&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    action.Completion.Wait();
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt;(AggregateException ex)
{
    Console.WriteLine(ex.InnerException.Message);
}&lt;/pre&gt;


&lt;p&gt;3. &lt;b&gt;&lt;i&gt;Fault Propagation&lt;/i&gt;&lt;/b&gt;: The Fault state of a source block can be automatically propagated to linked target blocks if the link between the blocks was configured with a DataflowLinkOptions that had its PropagateCompletion set to true.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;TransformBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; transformBlock = 
    &lt;span class="kwrd"&gt;new&lt;/span&gt; TransformBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;((x) =&amp;gt; 
{ 
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (x == 1) { &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;&amp;quot;Test&amp;quot;&lt;/span&gt;); } &lt;span class="kwrd"&gt;else&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; x; } 
});

BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bufferBlock = &lt;span class="kwrd"&gt;new&lt;/span&gt; BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();

transformBlock.LinkTo(bufferBlock, 
    &lt;span class="kwrd"&gt;new&lt;/span&gt; DataflowLinkOptions() { PropagateCompletion= &lt;span class="kwrd"&gt;true&lt;/span&gt;});

transformBlock.Post(1);
&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    bufferBlock.Completion.Wait();
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt;(AggregateException ex)
{
    Console.WriteLine(ex.InnerException.InnerException.Message);
}&lt;/pre&gt;


&lt;p&gt;4. &lt;b&gt;&lt;i&gt;Incorrect Interface Implementations&lt;/i&gt;&lt;/b&gt;: If a block is incorrectly implemented such that one of its interface methods used for inter-block messaging throws an exception, that exception may fault the block with which it’s communicating. For example, a source block might be incorrectly implemented such that its ConsumeMessage method throws. Any linked block that will try to consume the message will become faulted even if the incorrectly implemented block is not faulted. Similar behavior can be observed if an incorrectly implemented target throws from its OfferMessage method.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bufferBlock = &lt;span class="kwrd"&gt;new&lt;/span&gt; BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;(
    &lt;span class="kwrd"&gt;new&lt;/span&gt; DataflowBlockOptions() { BoundedCapacity = 1 });

InvalidSource&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; source = &lt;span class="kwrd"&gt;new&lt;/span&gt; InvalidSource&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;(2);

bufferBlock.Post(1);
&lt;span class="rem"&gt;//buffer is full so the message will be postponed&lt;/span&gt;

source.LinkTo(bufferBlock);

&lt;span class="rem"&gt;//make room for the new message to be consumed&lt;/span&gt;
&lt;span class="kwrd"&gt;int&lt;/span&gt; firstElement = bufferBlock.Receive();

&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    bufferBlock.Completion.Wait();
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt;(AggregateException ex)
{
    Console.WriteLine(ex.InnerException.Message);
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; InvalidSource&amp;lt;T&amp;gt; : ISourceBlock&amp;lt;T&amp;gt;
{
    T message;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; FaultedSource(T message)
    {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.message= message;
    }

    T ISourceBlock&amp;lt;T&amp;gt;.ConsumeMessage(
        DataflowMessageHeader messageHeader, ITargetBlock&amp;lt;T&amp;gt; target, 
        &lt;span class="kwrd"&gt;out&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; messageConsumed)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;&amp;quot;Test&amp;quot;&lt;/span&gt;);
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable LinkTo(ITargetBlock&amp;lt;T&amp;gt; target, 
        DataflowLinkOptions linkOptions)
    {
        target.OfferMessage(&lt;span class="kwrd"&gt;new&lt;/span&gt; DataflowMessageHeader(1), 
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.message, &lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;true&lt;/span&gt;);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;
    }

    &lt;span class="kwrd"&gt;void&lt;/span&gt; ISourceBlock&amp;lt;T&amp;gt;.ReleaseReservation(
        DataflowMessageHeader messageHeader, ITargetBlock&amp;lt;T&amp;gt; target)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }

    &lt;span class="kwrd"&gt;bool&lt;/span&gt; ISourceBlock&amp;lt;T&amp;gt;.ReserveMessage(
        DataflowMessageHeader messageHeader, ITargetBlock&amp;lt;T&amp;gt; target)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Complete()
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; Task Completion
    {
        get { &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException(); }
    }

    &lt;span class="kwrd"&gt;void&lt;/span&gt; IDataflowBlock.Fault(Exception exception)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }
}&lt;/pre&gt;


&lt;h3&gt;Behaviors of a “Faulted” Block&lt;/h3&gt;

&lt;p&gt;After a block becomes faulted:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It should stop processing additional messages.&lt;/li&gt;

  &lt;li&gt;It should clear its message queues, both input and output.&lt;/li&gt;

  &lt;li&gt;It should fault its Completion task.&lt;/li&gt;

  &lt;li&gt;If it is a target:&lt;/li&gt;

  &lt;ul&gt;
    &lt;li&gt;It should decline any further incoming messages.&lt;/li&gt;

    &lt;li&gt;It should release any reserved messages.&lt;/li&gt;

    &lt;li&gt;Optionally, it may reserve and then release any postponed messages to notify the sources they will never be needed.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;li&gt;If it is a source:&lt;/li&gt;

  &lt;ul&gt;
    &lt;li&gt;It should stop offering messages.&lt;/li&gt;

    &lt;li&gt;It should transfer the exception to any targets currently linked where those links were created with DataflowLinkOptions.PropagateCompletion == true.&lt;/li&gt;

    &lt;li&gt;It should unlink from currently linked targets&lt;/li&gt;
  &lt;/ul&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Behaviors of a network with “Faulted” blocks&lt;/h3&gt;

&lt;p&gt;1. Reserved Messages&lt;/p&gt;

&lt;p&gt;In order to avoid message corruption, a faulted block should clear its message queues and move into a Faulted state as soon as possible. There is a single scenario that does not obey to this rule: a source block holding a message reserved by a target. If a block that encounters an internal exception has a message that was reserved by a target, the reserved message must not be dropped, and the block should not be moved into the Faulted state until the message is released or consumed. Here is an example.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bufferBlock = &lt;span class="kwrd"&gt;new&lt;/span&gt; BufferBlock&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
ReservingTarget&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; target = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReservingTarget&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();

bufferBlock.LinkTo(target);
bufferBlock.Post(1);
bufferBlock.Post(2);
bufferBlock.Post(3);

&lt;span class="rem"&gt;//give time to have the message reserved&lt;/span&gt;
Thread.Sleep(1000);

((IDataflowBlock)bufferBlock).Fault(&lt;span class="kwrd"&gt;new&lt;/span&gt; Exception(&lt;span class="str"&gt;&amp;quot;Test&amp;quot;&lt;/span&gt;));
&lt;span class="kwrd"&gt;bool&lt;/span&gt; completionBlock = bufferBlock.Completion.Wait(2000);
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Block is completed {0}. &amp;quot;&lt;/span&gt;, completionBlock);

&lt;span class="rem"&gt;//consume the message and block will be completed&lt;/span&gt;
target.ConsumeMessage();

&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    bufferBlock.Completion.Wait();
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt; (AggregateException ex)
{
    Console.WriteLine(ex.InnerException.Message);
}

&lt;span class="kwrd"&gt;class&lt;/span&gt; ReservingTarget&amp;lt;T&amp;gt; : ITargetBlock&amp;lt;T&amp;gt;
{
    DataflowMessageHeader messageHeader;
    ISourceBlock&amp;lt;T&amp;gt; source;

    DataflowMessageStatus ITargetBlock&amp;lt;T&amp;gt;.OfferMessage(
        DataflowMessageHeader messageHeader, T messageValue, 
        ISourceBlock&amp;lt;T&amp;gt; source, &lt;span class="kwrd"&gt;bool&lt;/span&gt; consumeToAccept)
    {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.messageHeader = messageHeader;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.source = source;

        &lt;span class="rem"&gt;//reserve&lt;/span&gt;
        Task.Factory.StartNew(() =&amp;gt; 
            { source.ReserveMessage(messageHeader, &lt;span class="kwrd"&gt;this&lt;/span&gt;); });

        &lt;span class="kwrd"&gt;return&lt;/span&gt; DataflowMessageStatus.Postponed;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ConsumeMessage()
    {
        &lt;span class="kwrd"&gt;bool&lt;/span&gt; msgConsumeStatus = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.source.ConsumeMessage(&lt;span class="kwrd"&gt;this&lt;/span&gt;.messageHeader, 
            &lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;out&lt;/span&gt; msgConsumeStatus);
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Complete()
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; Task Completion
    {
        get { &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException(); }
    }

    &lt;span class="kwrd"&gt;void&lt;/span&gt; IDataflowBlock.Fault(Exception exception)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }
}&lt;/pre&gt;


&lt;p&gt;2. Hanging Networks&lt;/p&gt;

&lt;p&gt;Dataflow blocks may be written to expect a specific number of input messages offered to it. Especially in the case where an earlier block in the network might fault, it’s possible such a block may not receive the expected number of messages; in the faulted case, blocks will explicitly drop messages they’ve already processed but haven’t yet forwarded and they’ll decline further messages offered to them. There are two ways to observe that a block in a network faults:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Keep a reference to all the blocks in the network and use Task.WaitAll or Task.WhenAll to wait for them (synchronously or asynchronously). If a block faults, its Completion task will complete in the Faulted state.&lt;/li&gt;

  &lt;li&gt;Use DataflowLinkOptions with PropagateCompletion == true when building a linear network. That will propagate block completion from source to target. In this case it is enough to wait on the network leaf block.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Behavior of Extensions Methods on Faulted blocks&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Choose:&lt;/b&gt; If all provided blocks have faulted, the returned task will be completed in the Canceled state.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;LinkTo:&lt;/b&gt; If the source block is completed (faulted or otherwise), no link should be created. The IDisposable returned from the call will have a Dispose method that’s effectively a nop.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;OutputAvailableAsync:&lt;/b&gt; If the source block is faulted, the returned Task&amp;lt;Boolean&amp;gt; will be completed in the RanToCompletion state and with its Result equal to false.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;Post&lt;/b&gt;: If the target block is declining further messages (e.g. because it’s completed, because it experienced an unhandled exception and is shutting down, etc.), the result of the Post method will be false.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;Receive:&lt;/b&gt; If the source block is faulted, this will throw an InvalidOperationException.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;ReceiveAsync&lt;/b&gt;: If the source block is faulted, the returned Task will complete in the Faulted state with the InvalidOperationException representing no data available (just as in the Receive case).&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;SendAsync&lt;/b&gt;: As with Post, if the target block is declining further messages (e.g. because it’s completed, because it experienced an unhandeled exception and is shutting down, etc.), the returned task will complete in the RanToCompletion state with its Result equal to false.&lt;/li&gt;

  &lt;li&gt;&lt;b&gt;TryReceive&lt;/b&gt;: Trying to receive from a faulted block will return false.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;Exception Handling Design Guidelines for new Dataflow Blocks&lt;/h3&gt;

&lt;p&gt;It is recommended that new Dataflow blocks are implemented following the below guidelines:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Avoid throwing exceptions in the implementation of the block’s interface methods.&lt;/li&gt;

  &lt;li&gt;The block should propagate the completion state to a linked target if, and only if, the blocks were linked using DataflowLinkOptions that has its PropagateCompletion property set to true.&lt;/li&gt;

  &lt;li&gt;Consider faulting the block when an exception is raised during message processing.&lt;/li&gt;

  &lt;li&gt;Consider cleaning block’s input / output queues when the block moves into the Complete state.&lt;/li&gt;

  &lt;li&gt;Consider releasing the postponed messages when the block moves into the Complete state.&lt;/li&gt;
&lt;/ol&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235570" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Dataflow/">Dataflow</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>ConcurrentDictionary Performance Improvements in .NET 4.5</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/08/10235147.aspx</link><pubDate>Tue, 08 Nov 2011 22:16:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10235147</guid><dc:creator>Igor Ostrovsky - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10235147</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10235147</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/08/10235147.aspx#comments</comments><description>&lt;p&gt;ConcurrentDictionary is a popular concurrent data structure that was introduced in .NET 4. In the .NET 4.5 release, ConcurrentDictionary gets two performance improvements.&lt;/p&gt;  &lt;p&gt;One optimization is related to the way ConcurrentDictionary avoids torn reads and writes. To explain the background, all reference types and some value types are guaranteed to be read and written atomically by the Common Language Runtime, as defined in section 12.6.6 of the &lt;a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf"&gt;ECMA CLI&lt;/a&gt; specification. However, large value types such as System.Guid are not read and written atomically. So, if a thread writes values into a System.Guid field while another thread reads the values, the reader thread might observe a partly updated value that consists of bytes from the ‘old’ value mixed with bytes from the ‘new’ value. The reason behind this is that a write or a read of a System.Guid value is not atomic on X86/X64 machines.&lt;/p&gt;  &lt;p&gt;To avoid torn reads and writes, the .NET 4 ConcurrentDictionary wraps all values in a node object. To modify a value associated with some key, ConcurrentDictionary allocates a new node object.&lt;/p&gt;  &lt;p&gt;In .NET 4.5, ConcurrentDictionary&amp;lt;TKey,TValue&amp;gt; now avoids reallocating nodes on updates if TValue is a reference type or a small primitive value type (Int32, Single, Byte, etc.)&lt;/p&gt;  &lt;p&gt;The example below demonstrates the improvement:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Example1(&lt;span class="kwrd"&gt;int&lt;/span&gt; key)
{
    var d = &lt;span class="kwrd"&gt;new&lt;/span&gt; ConcurrentDictionary&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;,&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
    &lt;span class="kwrd"&gt;for&lt;/span&gt;(&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i&amp;lt;10000000; i++)
    {
        d[key] = i;
    }
}&lt;/pre&gt;


&lt;p&gt;Example1(0) executes about 10% faster in .NET 4.5 than it did in .NET 4.&lt;/p&gt;

&lt;p&gt;The difference becomes more prominent when multiple threads are involved: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Example2()
{
    Parallel.Invoke(
        () =&amp;gt; Example1(0),
        () =&amp;gt; Example1(1),
        () =&amp;gt; Example1(2),
        () =&amp;gt; Example1(3));
}&lt;/pre&gt;


&lt;p&gt;Example2() calls Example1() on four different threads with different key values. In .NET 4.5, Example2 executes about 30-40% faster than it did .NET 4.&lt;/p&gt;

&lt;p&gt;Another ConcurrentDictionary optimization that we introduced in .NET 4.5 is dynamic addition of locks. In .NET 4, the number of locks that protect a ConcurrentDictionary instance is fixed over the lifetime of the instance. By default, the number of locks is based on the number of processors, or alternatively, the user can provide a custom concurrency level.&lt;/p&gt;

&lt;p&gt;In practice, a large number of locks is often desirable for maximum throughput. On the other hand, we don’t want to allocate too many lock objects, especially if the ConcurrentDictionary only ends up storing only a small number of items. &lt;/p&gt;

&lt;p&gt;In .NET 4.5, ConcurrentDictionary will automatically add more locks as more values are stored in the dictionary. (Note that ConcurrentDictionary will not add more locks if the instance was initialized using one of the constructors that accept a concurrencyLevel argument.)&lt;/p&gt;

&lt;p&gt;This example demonstrates the benefit of dynamic lock addition:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Example3()
{
    var dict = &lt;span class="kwrd"&gt;new&lt;/span&gt; ConcurrentDictionary&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
    Action&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; helper = constant =&amp;gt;
    {
        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 10000000; i++)
        {
            dict[(constant + i) % 100000] = i;
        }
    };

    Parallel.Invoke(
        () =&amp;gt; helper(0),
        () =&amp;gt; helper(10000),
        () =&amp;gt; helper(20000),
        () =&amp;gt; helper(30000));
}&lt;/pre&gt;


&lt;p&gt;This example executes approximately 2.5 – 3X faster in .NET 4.5 compared to .NET 4 and demonstrates the combined effect of both optimizations (cheaper atomic updates and dynamic number of locks) acting together.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10235147" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Code+Samples/">Code Samples</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Coordination+Data+Structures/">Coordination Data Structures</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Updated Async CTP</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/11/01/10232099.aspx</link><pubDate>Tue, 01 Nov 2011 15:28:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10232099</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10232099</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10232099</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/11/01/10232099.aspx#comments</comments><description>&lt;p&gt;In April, we released the Async CTP Refresh, and since then we've seen fantastic adoption of the technology.&amp;nbsp; We've also seen the technology landscape evolve.&amp;nbsp; Windows Phone 7.5, aka "Mango", was released.&amp;nbsp; Silverlight 5 has had both a Beta and an RC release.&amp;nbsp; And there have been multiple patches to Visual Studio and the .NET Framework.&amp;nbsp; All of these have led to some issues with the Async CTP, which many users have run into and let us know about on the &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/async/threads"&gt;forums&lt;/a&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Some Visual Studio and .NET Framework patches have prevented some of you from installing the Async CTP Refresh, and they've even prevented some of you that already have the Async CTP installed from continuing to use it successfully.&lt;/li&gt;
&lt;li&gt;Windows Phone 7.1 SDK enables the development of "&lt;a href="http://msdn.microsoft.com/en-us/library/hh202942(v=VS.92).aspx"&gt;background agents&lt;/a&gt;".&amp;nbsp; However, these agents are restricted from referencing certain DLLs, some of which the AsyncCtpLibrary_Phone.dll happened to reference.&amp;nbsp; That meant you couldn't use the Async CTP in the development of such agents.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2011/09/01/10204554.aspx"&gt;Silverlight 5 now includes Tasks&lt;/a&gt;. And while that's awesome, it also means that there's then a conflict between the Task implementation included in Silverlight 5 and the Task implementation included in the CTP's AsyncCtpLibrary_Silverlight.dll, which makes it very challenging to use AsyncCtpLibrary_Silverlight.dll with Silverlight 5.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To address all of these problems, we've just released &lt;a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;amp;id=9983"&gt;v3 of the Async CTP&lt;/a&gt;.&amp;nbsp; The installer has been tested with all known Visual Studio and .NET Framework patches.&amp;nbsp; The AsyncCtpLibrary_Phone.dll has had the bad references removed so that it may be used to develop background agents.&amp;nbsp; And the CTP includes a new AsyncCtpLibrary_Silverlight5.dll, which may be used with Silverlight 5 RC (AsyncCtpLibrary_Silverlight.dll is still included and may be used for apps using Silverlight 4).&lt;/p&gt;
&lt;p&gt;(Especially for those of you that previously installed the Async CTP and that are planning to install the update, Lucian Wischik has some &lt;a href="http://blogs.msdn.com/b/lucian/archive/2011/11/01/async-ctp-v3-installation.aspx"&gt;good information on his blog&lt;/a&gt; about handling common installation problems.)&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10232099" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Silverlight/">Silverlight</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category></item><item><title>When at last you await</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229662.aspx</link><pubDate>Tue, 25 Oct 2011 05:36:49 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10229662</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10229662</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10229662</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229662.aspx#comments</comments><description>&lt;p&gt;When you start using async methods heavily, you’ll likely see a particular pattern of composition pop up from time to time.&amp;#160; Its structure is typically either of the form:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;async Task FooAsync()        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; … // some initialization code without awaits&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await BarAsync(…);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;or of the form:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;async Task&amp;lt;T&amp;gt; FooAsync()        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; … // some initialization code without awaits        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return await BarAsync(…);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A concrete example of this might be a FlushAsync method on a custom buffered stream, where the stream maintains a byte[] of data to write out, along with the number of bytes buffered, and flushing the buffer involves resetting the buffered count and writing the data out to the underlying wrapped stream, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;public override async Task FlushAsync()        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; int numBuffered = m_numBuffered;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; m_numBuffered = 0;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await m_wrappedStream.WriteAsync(m_buffer, 0, numBuffered);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When we find code that follows this particular pattern, we can employ an alternative.&amp;#160; Instead of the above, we could write this FlushAsync method as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;public override Task FlushAsync()        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; int numBuffered = m_numBuffered;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; m_numBuffered = 0;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return m_wrappedStream.WriteAsync(m_buffer, 0, numBuffered);         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The key difference here is that this method is no longer using the compiler support for writing async methods.&amp;#160; By removing the “async” keyword, this is just an ordinary method, rather than one that the compiler rewrites into a state machine.&amp;#160; And along with that, we’re now returning a Task created by the body of the method rather than relying on the compiler to create one for us.&lt;/p&gt;  &lt;p&gt;Why would we want to do this?&amp;#160; Purely as an optimization.&amp;#160; If the particular code in question is very performance-sensitive, you can save some cycles by avoiding the overhead necessary to support compiler-generated async methods.&amp;#160; When you use the async/await keywords, the compiler and Framework collude to generate a Task on your behalf to represent all of the async method’s processing.&amp;#160; In this case, however, we’re being handed a task to represent the last statement in the method, and thus it’s in effect already a representation of the entire method’s processing (as long as nothing in the preamble could throw an exception, since such an exception would directly escape the method rather than being stored into the returned task).&amp;#160; Since it already provides the representation we need, we can return it untouched to our caller, saving a level of indirection.&lt;/p&gt;  &lt;p&gt;For more information on performance and async methods, see the &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx"&gt;October 2011&lt;/a&gt; issue of MSDN Magazine.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10229662" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>Task.Run vs Task.Factory.StartNew</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx</link><pubDate>Mon, 24 Oct 2011 20:33:11 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10229468</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10229468</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10229468</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx#comments</comments><description>&lt;p&gt;In .NET 4, Task.Factory.StartNew was the primary method for scheduling a new task.&amp;#160; Many overloads provided for a highly configurable mechanism, enabling setting options, passing in arbitrary state, enabling cancellation, and even controlling scheduling behaviors.&amp;#160; The flip side of all of this power is complexity.&amp;#160; You need to know when to use which overload, what scheduler to provide, and the like. And “Task.Factory.StartNew” doesn’t exactly roll off the tongue, at least not quickly enough for something that’s used in such primary scenarios as easily offloading work to background processing threads.&lt;/p&gt;  &lt;p&gt;So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method.&amp;#160; This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters.&amp;#160; It’s a shortcut.&amp;#160; In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters.&amp;#160; When you pass an Action to Task.Run:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;Task.Run(someAction);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;that’s exactly equivalent to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;Task.Factory.StartNew(someAction,        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In this way, Task.Run can and should be used for the most common cases of simply offloading some work to be processed on the ThreadPool (what TaskScheduler.Default targets).&amp;#160; That doesn’t mean Task.Factory.StartNew will never again be used; far from it.&amp;#160; Task.Factory.StartNew still has many important (albeit more advanced) uses.&amp;#160; You get to control TaskCreationOptions for how the task behaves.&amp;#160; You get to control the scheduler for where the task should be queued to and run.&amp;#160; You get to use overloads that accept object state, which for performance-sensitive code paths can be used to avoid closures and the corresponding allocations.&amp;#160; For the simple cases, though, Task.Run is your friend.&lt;/p&gt;  &lt;p&gt;Task.Run provides eight overloads, to support all combinations of the following:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Task vs Task&amp;lt;TResult&amp;gt; &lt;/li&gt;    &lt;li&gt;Cancelable vs non-cancelable &lt;/li&gt;    &lt;li&gt;Synchronous vs asynchronous delegate &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The first two bullets should be self-explanatory.&amp;#160; For the first bullet, there are overloads that return Task (for operations that don’t have a result) and there are overloads that return Task&amp;lt;TResult&amp;gt; (for operations that have a result of type TResult).&amp;#160; There are also overloads that accept a CancellationToken, which enables the Task Parallel Library (TPL) to transition the task to a Canceled state if cancellation is requested prior to the task beginning its execution.&lt;/p&gt;  &lt;p&gt;The third bullet is more interesting, and is directly related to the async language support in C# and Visual Basic in Visual Studio 11.&amp;#160; Let’s consider Task.Factory.StartNew for a moment, as that will help to highlight what this distinction is.&amp;#160; If I write the following call:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Factory.StartNew(() =&amp;gt;        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task inner =Task.Factory.StartNew(() =&amp;gt; {});         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return inner;         &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;the type of ‘t’ is going to be Task&amp;lt;Task&amp;gt;; the task’s delegate is of type Func&amp;lt;TResult&amp;gt;, TResult in this case is a Task, and thus StartNew is returning a Task&amp;lt;Task&amp;gt;.&amp;#160; Similarly, if I were to change that to be:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Factory.StartNew(() =&amp;gt;        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;int&amp;gt; inner = Task.Factory.StartNew(() =&amp;gt; 42));         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return inner;         &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;the type of ‘t’ is now going to be Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;.&amp;#160; The task’s delegate is Func&amp;lt;TResult&amp;gt;, TResult is now Task&amp;lt;int&amp;gt;, and thus StartNew is returning Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;.&amp;#160; Why is this relevant?&amp;#160; Consider now what happens if I write the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Factory.StartNew(async delegate        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;By using the async keyword here, the compiler is going to map this delegate to be a Func&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;: invoking the delegate will return the Task&amp;lt;int&amp;gt; to represent the eventual completion of this call.&amp;#160; And since the delegate is Func&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;, TResult is Task&amp;lt;int&amp;gt;, and thus the type of ‘t’ is going to be Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;, not Task&amp;lt;int&amp;gt;.&lt;/p&gt;  &lt;p&gt;To handle these kinds of cases, in .NET 4 we introduced the Unwrap method.&amp;#160; Unwrap has two overloads, which are both extensions methods, one on type Task&amp;lt;Task&amp;gt; and one on type Task&amp;lt;Task&amp;lt;TResult&amp;gt;&amp;gt;.&amp;#160; We called this method Unwrap because it, in effect, “unwraps” the inner task that’s returned as the result of the outer task.&amp;#160; Calling Unwrap on a Task&amp;lt;Task&amp;gt; gives you back a new Task (which we often refer to as a proxy) which represents the eventual completion of the inner task.&amp;#160; Similarly, calling Unwrap on a Task&amp;lt;Task&amp;lt;TResult&amp;gt;&amp;gt; gives you back a new Task&amp;lt;TResult&amp;gt; which represents the eventual completion of that inner task. (In both cases, if the outer task is Faulted or Canceled, there is no inner task, since there’s no result from a task that doesn’t run to completion, so the proxy task then represents the state of the outer task.) Going back to the prior example, if I wanted ‘t’ to represent the return value of that inner task (in this case, the value 42), I could write:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Factory.StartNew(async delegate        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;})&lt;strong&gt;.Unwrap();&lt;/strong&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The ‘t’ variable will now be of type Task&amp;lt;int&amp;gt;, representing the result of that asynchronous invocation.&lt;/p&gt;  &lt;p&gt;Enter Task.Run.&amp;#160; Because we expect it to be so common for folks to want to offload work to the ThreadPool, and for that work to use async/await, we decided to build this unwrapping functionality into Task.Run.&amp;#160; That’s what’s referred to by the third bullet above.&amp;#160; There are overloads of Task.Run that accept Action (for void-returning work), Func&amp;lt;TResult&amp;gt; (for TResult-returning work), Func&amp;lt;Task&amp;gt; (for void-returning async work), and Func&amp;lt;Task&amp;lt;TResult&amp;gt;&amp;gt; (for TResult-returning async work).&amp;#160; Internally, then, Task.Run does the same kind of unwrapping that’s shown with Task.Factory.StartNew above.&amp;#160; So, when I write:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Run(async delegate        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;the type of ‘t’ is Task&amp;lt;int&amp;gt;, and the implementation of this overload of Task.Run is basically equivalent to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;var t = Task.Factory.StartNew(async delegate        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As mentioned before, it’s a shortcut.&lt;/p&gt;  &lt;p&gt;All of this then means that you can use Task.Run either with either regular lambdas/anonymous methods or with async lambdas/anonymous methods, and the right thing will just happen.&amp;#160; If I wanted to offload this work to the ThreadPool and await its result, e.g.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;int result = await Task.Run(async () =&amp;gt;        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;});&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;the type of &lt;em&gt;result&lt;/em&gt; will be int, just as you’d expect, and approximately one second after this work is invoked, the &lt;em&gt;result&lt;/em&gt; variable be set to the value 42.&lt;/p&gt;  &lt;p&gt;Interestingly, the new await keyword can almost be thought of as a language equivalent to the Unwrap method.&amp;#160; So, if we return back to our Task.Factory.StartNew example, I could rewrite the last snippet above as follows using Unwrap:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;int result = await Task.Factory.StartNew(async delegate        &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;or, instead of using Unwrap, I could use a second await:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Consolas"&gt;int result = &lt;strong&gt;await&lt;/strong&gt; await Task.Factory.StartNew(async delegate         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; await Task.Delay(1000);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return 42;         &lt;br /&gt;}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;“await await” here is not a typo.&amp;#160; Task.Factory.StartNew is returning a Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;.&amp;#160; Await’ing that Task&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt; returns a Task&amp;lt;int&amp;gt;, and awaiting that Task&amp;lt;int&amp;gt; returns an int.&amp;#160; Fun, right?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10229468" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Task+Parallel+Library/">Task Parallel Library</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Parallel+Extensions/">Parallel Extensions</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4/">.NET 4</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item><item><title>New articles on async/await in MSDN Magazine</title><link>http://blogs.msdn.com/b/pfxteam/archive/2011/10/03/10219193.aspx</link><pubDate>Mon, 03 Oct 2011 15:47:41 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10219193</guid><dc:creator>Stephen Toub - MSFT</dc:creator><slash:comments>12</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/rsscomments.aspx?WeblogPostID=10219193</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/pfxteam/commentapi.aspx?WeblogPostID=10219193</wfw:comment><comments>http://blogs.msdn.com/b/pfxteam/archive/2011/10/03/10219193.aspx#comments</comments><description>&lt;p&gt;&lt;img style="display: inline; float: right" align="right" src="http://i.msdn.microsoft.com/hh463583.cover_lrg(en-us,MSDN.10).png" /&gt;The &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh463583.aspx"&gt;October 2011 issue&lt;/a&gt; of MSDN Magazine is now available online.&amp;#160; In it, you can find three articles about the new async/await features of C# and Visual Basic.&amp;#160; While the articles can stand alone, they were written with each other in mind in order to provide a 1-2-3 on-ramp into the world of asynchronous programming with these new language and library features.&lt;/p&gt;  &lt;p&gt;Here they are.&amp;#160; If you read them all, we recommend you read them in the following order:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456401.aspx"&gt;Asynchronous Programming: Easier Asynchronous Programming with the New Visual Studio Async CTP&lt;/a&gt; by &lt;strong&gt;Eric Lippert&lt;/strong&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456403.aspx"&gt;Asynchronous Programming: Pause and Play with Await&lt;/a&gt; by &lt;strong&gt;Mads Torgersen&lt;/strong&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx"&gt;Asynchronous Programming: Understanding the Costs of Async and Await&lt;/a&gt; by &lt;strong&gt;Stephen Toub&lt;/strong&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10219193" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/MSDN/">MSDN</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Article+Summary/">Article Summary</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/Async/">Async</category><category domain="http://blogs.msdn.com/b/pfxteam/archive/tags/-NET+4-5/">.NET 4.5</category></item></channel></rss>
