<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.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>Jon Skeet: Coding Blog : Eduasync, async</title><link>http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/async/default.aspx</link><description>Tags: Eduasync, async</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>Eduasync 20: Changes between the VS11 Preview and the Visual Studio 11 Beta</title><link>http://msmvps.com/blogs/jon_skeet/archive/2012/03/06/eduasync-20-changes-between-the-vs11-preview-and-the-visual-studio-11-beta.aspx</link><pubDate>Tue, 06 Mar 2012 19:54:54 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1807031</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1807031</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1807031</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/03/06/eduasync-20-changes-between-the-vs11-preview-and-the-visual-studio-11-beta.aspx#comments</comments><description>&lt;p&gt;A while I ago I &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2012/01/12/eduasync-part-18-changes-between-the-async-ctp-and-the-visual-studio-11-preview.aspx"&gt;blogged about&lt;/a&gt; what had changed under the hood of async between the CTP and the VS11 Preview. Well, now that the VS11 Beta is out, it&amp;#39;s time to do it all again...&lt;/p&gt;  &lt;p&gt;Note that the code in this post &lt;em&gt;is &lt;/em&gt;in the &lt;a href="http://eduasync.googlecode.com"&gt;Eduasync codebase&lt;/a&gt;, under a different solution (Eduasync VS11.sln). Many of the old existing projects won&amp;#39;t compile with VS11 beta, but I&amp;#39;d rather leave them as they are for posterity, showing the evolution of the feature.&lt;/p&gt;  &lt;p&gt;Stephen Toub has an &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/02/29/10274035.aspx"&gt;excellent blog post&lt;/a&gt; covering some of this, so while I&amp;#39;ll &lt;em&gt;mention&lt;/em&gt; things he&amp;#39;s covered, I won&amp;#39;t go into much detail about them. Let&amp;#39;s start off there though...&lt;/p&gt;  &lt;p&gt;(EDIT: Stephen has also mailed me with some corrections, which I&amp;#39;ve edited in - mostly without indication, as the post has been up for less than seven hours, and it&amp;#39;ll make for a better reading experience.)&lt;/p&gt;  &lt;h2&gt;Awaiter pattern changes&lt;/h2&gt;  &lt;p&gt;The awaiter pattern is now not &lt;em&gt;just&lt;/em&gt; a pattern. The IsCompleted property and GetResult method are still &amp;quot;loose&amp;quot; but &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.inotifycompletion.oncompleted(v=vs.110).aspx"&gt;OnCompleted&lt;/a&gt; is now part of an interface: &lt;a href="http://msdn.microsoft.com/en-us/library/hh472348(v=vs.110).aspx"&gt;INotifyCompletion&lt;/a&gt;. Awaiters &lt;em&gt;have&lt;/em&gt; to implement INotifyCompleted, but may &lt;em&gt;also&lt;/em&gt; implement &lt;a href="http://msdn.microsoft.com/en-us/library/hh472362(v=vs.110).aspx"&gt;ICriticalNotifyCompletion&lt;/a&gt; and its &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.icriticalnotifycompletion.unsafeoncompleted(v=vs.110).aspx"&gt;UnsafeOnCompleted&lt;/a&gt; method.&lt;/p&gt;  &lt;p&gt;The OnCompleted method is just as it was before, and needs to flow the execuction context; the UnsafeOnCompleted method is simpler, as it &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; need to flow the execution context. All of this only matters if you&amp;#39;re implementing your own awaiters, of course. (More details in Stephen&amp;#39;s blog post. I&amp;#39;ve found this area somewhat confusing, so please do read his post carefully!)&lt;/p&gt;  &lt;h2&gt;Skeleton method changes&lt;/h2&gt;  &lt;p&gt;Just as I have previously, I&amp;#39;m using the (entirely unofficial) term &amp;quot;skeleton method&amp;quot; to mean the very short method created by the compiler with the same signature as an async method: this is the entry point to the async method, effectively, which creates and starts the state machine containing all the &lt;em&gt;real&lt;/em&gt; logic.&lt;/p&gt;  &lt;p&gt;There are two changes I&amp;#39;ve noticed in the skeleton method. Firstly, for some reason the state machine state numbers have changed. Whereas previously a state number of 0 meant &amp;quot;initial or running&amp;quot;, positive values meant &amp;quot;between calls, or navigating back to the await expression&amp;quot; and -1 meant &amp;quot;finished&amp;quot;, now -1 means &amp;quot;initial or running&amp;quot;, non-negative means &amp;quot;between calls, or navigating back to await expression&amp;quot; and -2 means &amp;quot;finished&amp;quot;. It&amp;#39;s not clear why this change has been made, given that it requires an extra assignment at the start of every skeleton method (to set the state to -1).&lt;/p&gt;  &lt;p&gt;More importantly, the skeleton method no longer calls MoveNext directly on the state machine that it&amp;#39;s built. Instead, it calls &lt;a href="http://msdn.microsoft.com/en-us/library/hh472313(v=vs.110).aspx"&gt;Start&amp;lt;TStateMachine&amp;gt;&lt;/a&gt; on the &lt;a href="http://msdn.microsoft.com/en-us/library/hh138506(v=vs.110).aspx"&gt;AsyncTaskMethodBuilder&amp;lt;T&amp;gt;&lt;/a&gt; (or whichever method builder it&amp;#39;s using). It passes the state machine by reference (presumably for efficiency), and TStateMachine is constrained to implement the now-public-and-in-mscorlib &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine(v=vs.110).aspx"&gt;IAsyncStateMachine&lt;/a&gt; interface. I&amp;#39;ll come back to the relationship between the state machine and the builder later on.&lt;/p&gt;  &lt;h2&gt;Task caching&lt;/h2&gt;  &lt;p&gt;(Code is in project 30: &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FTaskCaching"&gt;TaskCaching&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;It&amp;#39;s possible for an async method to complete entirely synchronously. In this situation, the result is known before the method returns, and the task returned by the method is already in the RanToCompletionState. If two tasks have already run to completion with the same value, they can be (apparently) regarded as equivalent... so the beta now caches a task in this situation, for some types and values. (Apparently the preview cached too, but I hadn&amp;#39;t noticed, and the beta caches more.) According to my experiments and some comments:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;For int, tasks with values -1 to 8 inclusive are cached &lt;/li&gt;    &lt;li&gt;For bool, both values (true and false)&lt;/li&gt;    &lt;li&gt;For char, byte, sbyte, short, ushort, uint, long, ulong, IntPtr and UIntPtr tasks with value 0 (or &amp;#39;\0&amp;#39;) are cached &lt;/li&gt;    &lt;li&gt;For reference types, null is cached&lt;/li&gt;    &lt;li&gt;For other types, no tasks are cached&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;EDIT: After they&amp;#39;ve completed, tasks are normally immutable &lt;em&gt;except for disposal&lt;/em&gt; - the cached tasks are tweaked slightly to make disposal a no-op. &lt;/p&gt;  &lt;h2&gt;State machine interface changes&lt;/h2&gt;  &lt;p&gt;In the VS11 preview release, each state machine implemented an interface, but that interface was internal to the generated assembly, and contained a single method (SetMoveNextDelegate). It&amp;#39;s now a public interface with two methods:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine.movenext(v=vs.110).aspx"&gt;MoveNext&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine.setstatemachine(v=vs.110).aspx"&gt;SetStateMachine&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Personally I&amp;#39;m not keen on the naming of &amp;quot;MoveNext&amp;quot; - I can&amp;#39;t help but feel that if we didn&amp;#39;t have the &amp;quot;naming baggage&amp;quot; of IEnumerator and the fact that at least early on, the code generator was very similar to that used for iterator blocks, we&amp;#39;d have something different. (It &lt;em&gt;is&lt;/em&gt; moving to the next state of the state machine, but it still doesn&amp;#39;t quite feel right.) I&amp;#39;d favour something like &amp;quot;ContinueExecution&amp;quot;. However, it doesn&amp;#39;t matter - it obviously does what you&amp;#39;d expect, and you&amp;#39;re not going to be calling this yourself.&lt;/p&gt;  &lt;p&gt;SetStateMachine is a stranger beast. The documentation states:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Configures the state machine with a heap-allocated replica.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;... which says almost nothing, really. The implementation is always simple, just like SetMoveNextDelegate was, although this time it delegates to the builder for the real work (a common theme, as we&amp;#39;ll see):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;void&lt;/span&gt; IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;t__builder.SetStateMachine(param0);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.asynctaskmethodbuilder.setstatemachine(v=vs.110).aspx"&gt;AsyncTaskMethodBuilder.SetStateMachine&lt;/a&gt; is also documented pretty sparsely:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Associates the builder with the specified state machine.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Again, no real help. However, we&amp;#39;ll see that it&amp;#39;s the &lt;em&gt;builder&lt;/em&gt; which is responsible for calling OnContinue now, and as it can call MoveNext on an IStateMachine, it makes sense to tell it which state machine it&amp;#39;s associated with... but can&amp;#39;t it do that directly?&lt;/p&gt;  &lt;p&gt;Well, not quite. The problem (as I understand it) is around when boxing occurs. We initially create the state machine on the stack, and it contains the builder. (Both are structs.) That&amp;#39;s fine until we need a continuation, but then we&amp;#39;ve got to be able to get back to the current state later, after the current stack frame has been blown away. So we need to box the state machine. That will create a &lt;em&gt;copy&lt;/em&gt; of the current builder (within the box). We need the builder within the boxed state machine to contain a reference to the same box. So the order has to be:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Box the state machine &lt;/li&gt;    &lt;li&gt;Tell the state machine about the boxed reference &lt;/li&gt;    &lt;li&gt;The state machine tells its nested builder about the boxed reference &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Back when the state machine was in charge of the boxing, this went via the delegate: the act of creating the box was implicit when creating the delegate, and then casting the delegate target to the interface type allowed a reference to the newly-created delegate to be set within the copy. This is similar, but using the builder instead. It&amp;#39;s hard to follow, but of course it&amp;#39;s not going to matter.&lt;/p&gt;  &lt;h2&gt;State machine field changes&lt;/h2&gt;  &lt;p&gt;There are various kinds of fields in the state machine:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Those corresponding with local variables and parameters in the async method &lt;/li&gt;    &lt;li&gt;The state &lt;/li&gt;    &lt;li&gt;The field(s) associated with awaiters &lt;/li&gt;    &lt;li&gt;(In the preview/beta) The field associated with the &amp;quot;current execution stack&amp;quot; at the point of an await expression &lt;/li&gt;    &lt;li&gt;(In the CTP) An unused &amp;quot;disposing&amp;quot; field &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of these, I believe only the awaiters have actually changed, but before we talk about that, let&amp;#39;s revisit local variables.&lt;/p&gt;  &lt;h3&gt;Local variable hoisting&lt;/h3&gt;  &lt;p&gt;I&amp;#39;ve just noticed that the local variables are only hoisted to fields when its scope contains an await expressions, but in that case &lt;em&gt;all&lt;/em&gt; local variables of that scope are hoisted, whether or not they&amp;#39;re used &amp;quot;across&amp;quot; awaits. It would be possible to hoist only those which need to be maintained between executions, but then you wouldn&amp;#39;t be able to see the others when debugging, which would be somewhat confusing. Likewise local variables of the same type which are never propagated across the same await &lt;em&gt;could&lt;/em&gt; be aliased. For example, consider this async method:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; M(Random rng)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x = rng.Next(1000);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; y = x + rng.Next(1000);     &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; &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Yield();     &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; &lt;span class="ValueType"&gt;int&lt;/span&gt; z = y + rng.Next(1000);     &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; &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Yield();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; z;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;If the compiler could be confident you didn&amp;#39;t need to debug through this code, it &lt;em&gt;could&lt;/em&gt; make do with one field of type &amp;quot;Random&amp;quot; and one field of type &amp;quot;int&amp;quot; - x can be a completely local variable in MoveNext (it&amp;#39;s not used between two awaits) and y and z can be aliased (we never need the value of y after we&amp;#39;ve first written to z).&lt;/p&gt;  &lt;p&gt;Local variable aliasing probably isn&amp;#39;t particularly useful for &amp;quot;normal&amp;quot; methods as the JIT may be able to do it (so long as you don&amp;#39;t have a debugger attached, potentially) but in this case we expect the state machine to be boxed at some point, so potentially &lt;em&gt;does&lt;/em&gt; make a difference (while the stack is typically reasonably small, you could have a &lt;em&gt;lot&lt;/em&gt; of outstanding async methods in some scenarios). Maybe in a future release, the C# compiler could have an aggressive optimization mode around this, to be turned on explicitly. (I don&amp;#39;t think it should be&amp;#160; a particularly high priority, mind you.)&lt;/p&gt;  &lt;h3&gt;Awaiter fields&lt;/h3&gt;  &lt;p&gt;(Code is in project 31, &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FAwaiterFields"&gt;AwaiterFields&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Awaiter fields have changed a bit over the course of async&amp;#39;s history.&lt;/p&gt;  &lt;p&gt;In the CTPs (all of them, I believe) each await expression had its own awaiter field in the state machine, with a type corresponding to the declared awaiter type from the awaitable. (Remember that the awaitable is the thing you await, such as a task, and the awaiter is what you get back from calling GetAwaiter on the awaitable).&lt;/p&gt;  &lt;p&gt;In the VS11 Preview, there was always a single awaiter field of type object. From what I saw, it was usually populated with a single-element array containing an awaiter. For value type awaiters (i.e. where the awaiter is a struct) this is somewhat similar to boxing, but maintaining strong typing, so calls to IsCompleted etc can still be made. It&amp;#39;s possible that reference type awaiters were stored without the array creation, as it would serve no purpose. (I don&amp;#39;t have any machines with just the preview installed to verify this.)&lt;/p&gt;  &lt;p&gt;In the Beta, we have a mixture. If there are any reference type awaiters, they all end up being stored in a single field of type object, which is then cast back to the actual type when required. (Don&amp;#39;t forget that only one awaiter can be &amp;quot;active&amp;quot; at a time, which makes this possible.) This includes awaiters of an interface type - it&amp;#39;s only the &lt;em&gt;compile-time&lt;/em&gt; type declared as the return type of the GetAwaiter method of the awaitable which is important.&lt;/p&gt;  &lt;p&gt;If any of the awaiter types are value types, each of these types gets its own field. So there might be a TaskAwaiter&amp;lt;int&amp;gt; field and a TaskAwaiter&amp;lt;string&amp;gt; field, for example. However, there can still be &amp;quot;sharing&amp;quot; going on: if there are multiple await expressions all of the same value type awaiter, they will all share a single field. (This all feels a &lt;em&gt;little&lt;/em&gt; like the JITting of generics, but it&amp;#39;s somewhat coincidental.)&lt;/p&gt;  &lt;h2&gt;MoveNext method changes&lt;/h2&gt;  &lt;p&gt;(Code is in project 32, BetaStateMachine)&lt;/p&gt;  &lt;p&gt;As I&amp;#39;ve mentioned earlier, the builder is now responsible for a lot more of the work than it was in earlier versions. The majority of the code remains the same as far as I can tell, in terms of handling branching, evaluating expressions with multiple await expressions and so on.&amp;#160; The code in the source repository shows what the complete state machine looks like, but for the sake of clarity, I&amp;#39;ll just focus on a single snippet. If we have an await expression like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;await&lt;/span&gt; x; &lt;/div&gt;  &lt;p&gt;then the state machine code in the VS11 Preview would look something like this:&lt;/p&gt;  &lt;div class="code"&gt;localTaskAwaiter = x.GetAwaiter();    &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (localTaskAwaiter.IsCompleted)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; AwaitCompleted;     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.state = 1;     &lt;br /&gt;TaskAwaiter[] awaiterArray = { localTaskAwaiter };     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.awaiter = awaiterArray;     &lt;br /&gt;Action continuation = &lt;span class="Keyword"&gt;this&lt;/span&gt;.MoveNextDelegate;     &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (continuation == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = &lt;span class="Keyword"&gt;this&lt;/span&gt;.builder.Task;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; continuation = MoveNext;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ((IStateMachine) continuation.Target).SetMoveNextDelegate(continuation);     &lt;br /&gt;}     &lt;br /&gt;awaiterArray[0].OnCompleted(continuation);     &lt;br /&gt;...     &lt;br /&gt;&lt;span class="Statement"&gt;return&lt;/span&gt;; &lt;/div&gt;  &lt;p&gt;(That&amp;#39;s just setting up the await, of course - there&amp;#39;s then the bit where the result is fetched, but that&amp;#39;s less interesting. There&amp;#39;s also the matter of doFinallyBodies.)&lt;/p&gt;  &lt;p&gt;In the VS11 Beta, it&amp;#39;s something this instead (for an awaiter type &amp;quot;AwaiterType&amp;quot; which implements ICriticalNotifyCompletion, in a state machine of type ThisStateMachine).&lt;/p&gt;  &lt;div class="code"&gt;localAwaiter = x.GetAwaiter();    &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (!localAwaiter.IsCompleted)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state = 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; awaiterField = localAwaiter;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; builder.AwaitUnsafeOnCompleted&amp;lt;AwaiterType, ThisStateMachine&amp;gt;(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; localAwaiter, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;this&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;If the awaiter type only implements INotifyCompletion, it calls &lt;a href="http://msdn.microsoft.com/en-us/library/hh472321(v=vs.110).aspx"&gt;AwaitOnCompleted&lt;/a&gt; instead. Note how the calls are generic (but both type variables are constrained to implement appropriate interfaces) which avoids boxing.&lt;/p&gt;  &lt;p&gt;The call to the builder will call &lt;em&gt;back&lt;/em&gt; to the state machine&amp;#39;s SetStateMachine method if this is the first awaiter that hasn&amp;#39;t already completed within this execution of the async method. So that handles the section which checked for the continuation being null in the first block of code. Most of the rest of the change is explained by the difference in awaiter types, and obviously AwaitOnCompleted/AwaitUnsafeOnCompleted &lt;em&gt;also&lt;/em&gt; ends up calling into OnCompleted on the awaiter itself.&lt;/p&gt;  &lt;h2&gt;Mutable value type awaiters&lt;/h2&gt;  &lt;p&gt;(Code is in project 32, &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FMutableAwaiters"&gt;MutableAwaiters&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;One subtle difference which &lt;em&gt;really&lt;/em&gt; shouldn&amp;#39;t hurt people but is fun to explore is what happens if you have an awaiter which is a mutable value type. Due to the way awaiters were carefully handled pre-beta, mutations which were conducted as part of OnCompleted would still be visible in GetResult. That&amp;#39;s &lt;em&gt;not&lt;/em&gt; the case in the beta (as Stephen mentions in his blog post). Mind you, it doesn&amp;#39;t mean that &lt;em&gt;all&lt;/em&gt; mutations will be ignored... just ones in OnCompleted. A mutation from IsCompleted is still visible, as shown here:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; MutableAwaiter : INotifyCompletion     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; message;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; MutableAwaiter(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; message)     &lt;br /&gt;&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; &lt;span class="Keyword"&gt;this&lt;/span&gt;.message = message;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted     &lt;br /&gt;&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; get     &lt;br /&gt;&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; message = &lt;span class="String"&gt;&amp;quot;Set in IsCompleted&amp;quot;&lt;/span&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; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;false&lt;/span&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; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action action)     &lt;br /&gt;&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; message = &lt;span class="String"&gt;&amp;quot;Set in OnCompleted&amp;quot;&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Ick! Completes inline. Never mind, it&amp;#39;s only a demo...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; action();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; GetResult()     &lt;br /&gt;&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; &lt;span class="Statement"&gt;return&lt;/span&gt; message;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;What would you expect to be returned from this awaiter? You can verify that all three members are called... but &amp;quot;Set in IsCompleted&amp;quot; is returned. That&amp;#39;s because IsCompleted is called &lt;em&gt;before&lt;/em&gt; the awaiter value is copied into a field within the state machine. Even though the state machine passes the awaiter by reference, it&amp;#39;s passing the &lt;em&gt;local&lt;/em&gt; variable, which is of course a separate variable from the field.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;absolutely not&lt;/em&gt; suggesting that you should rely on any of this behaviour. If you really need to be able to mutate your awaiter, make it a reference type.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;The main changes in the Beta are around the interactions between the AsyncTaskMethodBuilder (et al) and the state machine, including the new interfaces for awaiters. There&amp;#39;s been quite a bit of optimization, although I still see room for a bit more:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;When there&amp;#39;s only a single kind of reference type awaiter, the field for storing it could be of that type rather than of type object, removing the need for an execution-time cast &lt;/li&gt;    &lt;li&gt;The &amp;quot;stack&amp;quot; variable could be removed in some cases, and made into a specific type in many others &lt;/li&gt;    &lt;li&gt;With appropriate optimization flags, local variables which aren&amp;#39;t used await expressions could stay local to the state machine instead of being hoisted, and hoisted variables could be aliased in some cases. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;One thing which concerns me slightly is how the C# language specification is going to change - the addition of the new interfaces is definitely going to mean more complexity from this previously &amp;quot;tidy&amp;quot; feature. I&amp;#39;m sure it&amp;#39;s worth it for the sake of efficiency and the like, but part of me sighs at every added tweak.&lt;/p&gt;  &lt;p&gt;So, is this now close to the finished version of async? Only time will tell. I haven&amp;#39;t checked whether dynamic awaitables have finally been introduced... if they have, I&amp;#39;ll put that in the next post.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1807031" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 19: ordering by completion, ahead of time...</title><link>http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx</link><pubDate>Mon, 16 Jan 2012 22:22:43 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1804970</guid><dc:creator>skeet</dc:creator><slash:comments>18</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1804970</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1804970</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx#comments</comments><description>&lt;p&gt;Today&amp;#39;s post involves the &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FMagicOrdering"&gt;MagicOrdering project&lt;/a&gt; in source control (project 28).&lt;/p&gt;  &lt;p&gt;When I wrote &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/11/22/eduasync-part-16-example-of-composition-majority-voting.aspx"&gt;part 16 of Eduasync&lt;/a&gt;, showing composition in the form of majority voting, one reader mailed me a &lt;em&gt;really&lt;/em&gt; interesting suggestion. We don&amp;#39;t really need to wait for &lt;em&gt;any&lt;/em&gt; of the tasks to complete on each iteration of the loop - we only need to wait for the &lt;em&gt;next&lt;/em&gt; task to complete. Now that sounds impossible - sure, it&amp;#39;s great if we know the completion order of the tasks, but half the point of asynchrony is that many things can be happening at once, and we don&amp;#39;t know when they&amp;#39;ll complete. However, it&amp;#39;s not as silly as it sounds.&lt;/p&gt;  &lt;p&gt;If you give me a collection of tasks, I&amp;#39;ll give you back another collection of tasks which will return the same results - but I&amp;#39;ll order them so that the first returned task will have the same result as whichever of your original tasks completes first, and the second returned task will have the same result as whichever of your original tasks completes second, and so on. They won&amp;#39;t be the &lt;em&gt;same&lt;/em&gt; tasks as you gave me, reordered - but they&amp;#39;ll be tasks with the same results. I&amp;#39;ll propagate cancellation, exceptions and so on.&lt;/p&gt;  &lt;p&gt;It still sounds impossible... until you realize that I don&amp;#39;t have to associate one of my returned tasks with one of your original tasks &lt;em&gt;until it has completed&lt;/em&gt;. Before anything has completed, all the tasks look the same. The trick is that as soon as I see one of your tasks complete, I can fetch the result and propagate it to the first of the tasks I&amp;#39;ve returned to you, using TaskCompletionSource&amp;lt;T&amp;gt;. When the second of your tasks completes, I propagate the result to the second of the returned tasks, etc. This is all quite easy using &lt;a href="http://msdn.microsoft.com/en-us/library/dd235663.aspx"&gt;Task&amp;lt;T&amp;gt;.ContinueWith&lt;/a&gt; - barring a few caveats I&amp;#39;ll mention later on.&lt;/p&gt;  &lt;p&gt;Once we&amp;#39;ve built a method to do this, we can then &lt;em&gt;really easily&lt;/em&gt; build a method which is the async equivalent of &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx"&gt;Parallel.ForEach&lt;/a&gt; (and indeed you could write multiple methods for the various overloads). This will execute a specific action on each task in turn, as it completes... it&amp;#39;s &lt;em&gt;like&lt;/em&gt; repeatedly calling &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenany(v=vs.110).aspx"&gt;Task.WhenAny&lt;/a&gt;, but we only actually need to wait for one task at a time, because we know that the first task in our &amp;quot;completion ordered&amp;quot; collection will be the first one to complete (duh).&lt;/p&gt;  &lt;h3&gt;Show me the code!&lt;/h3&gt;  &lt;p&gt;Enough description - let&amp;#39;s look at how we&amp;#39;ll demonstrate both methods, and then how we implement them.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task PrintDelayedRandomTasksAsync()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Random rng = &lt;span class="Keyword"&gt;new&lt;/span&gt; Random();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; values = Enumerable.Range(0, 10).Select(_ =&amp;gt; rng.Next(3000)).ToList();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Initial order: {0}&amp;quot;&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;.Join(&lt;span class="String"&gt;&amp;quot; &amp;quot;&lt;/span&gt;, values));     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; tasks = values.Select(DelayAsync);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; ordered = OrderByCompletion(tasks);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;In order of completion:&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; ForEach(ordered, Console.WriteLine);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Returns a task which delays (asynchronously) by the given number of milliseconds,&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// then return that same number back.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; DelayAsync(&lt;span class="ValueType"&gt;int&lt;/span&gt; delayMillis)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; TaskEx.Delay(delayMillis);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; delayMillis;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The idea is that we&amp;#39;re going to create 10 tasks which each just wait for some random period of time, and return the same time period back. We&amp;#39;ll create them in any old order - but obviously they should complete in (at least roughly) the same order as the returned numbers.&lt;/p&gt;  &lt;p&gt;Once we&amp;#39;ve created the collection of tasks, we&amp;#39;ll call OrderByCompletion to create a &lt;em&gt;second&lt;/em&gt; collection of tasks, returning the same results but this time in completion order - so ordered.ElementAt(0) will be the first task to complete, for example.&lt;/p&gt;  &lt;p&gt;Finally, we call ForEach and pass in the ordered task collection, along with Console.WriteLine as the action to take with each value. We await the resulting Task to mimic blocking until the foreach loop has finished. Note that we &lt;em&gt;could&lt;/em&gt; make this a non-async method and just return the task returned by ForEach, given that that&amp;#39;s our only await expression and it&amp;#39;s right at the end of the method. This would be marginally faster, too - there&amp;#39;s no need to build an extra state machine. See &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx"&gt;Stephen Toub&amp;#39;s article about async performance&lt;/a&gt; for more information.&lt;/p&gt;  &lt;h3&gt;ForEach&lt;/h3&gt;  &lt;p&gt;I&amp;#39;d like to get ForEach out of the way first, as it&amp;#39;s so simple: it&amp;#39;s literally just iterating over the tasks, awaiting them and propagating the result to the action. We get the &amp;quot;return a task which will wait until we&amp;#39;ve finished&amp;quot; for free by virtue of making it an async method.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Executes the given action on each of the tasks in turn, in the order of&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// the sequence. The action is passed the result of each task.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task ForEach&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; tasks, Action&amp;lt;T&amp;gt; action)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; task &lt;span class="Statement"&gt;in&lt;/span&gt; tasks)     &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; T value = &lt;span class="Modifier"&gt;await&lt;/span&gt; task;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; action(value);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Simple, right? Let&amp;#39;s get onto the meat...&lt;/p&gt;  &lt;h5&gt;OrderByCompletion&lt;/h5&gt;  &lt;p&gt;This is the tricky bit, and I&amp;#39;ve actually split it into two methods to make it slightly easier to comprehend. The PropagateResult method feels like it could be useful in other composition methods, too.&lt;/p&gt;  &lt;p&gt;The basic plan is:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Copy the input tasks to a list: we need to work out how many there are &lt;em&gt;and&lt;/em&gt; iterate over them, so let&amp;#39;s make sure we only iterate once &lt;/li&gt;    &lt;li&gt;Create a collection of TaskCompletionSource&amp;lt;T&amp;gt; references, one for each input task. Note that we&amp;#39;re not associating any particular input task with any particular completion source - we just need the same number of them &lt;/li&gt;    &lt;li&gt;Declare an integer to keep track of &amp;quot;the next available completion source&amp;quot; &lt;/li&gt;    &lt;li&gt;Attach a continuation to each input task which will be increment the counter we&amp;#39;ve just declared, and propagate the just-completed task&amp;#39;s status &lt;/li&gt;    &lt;li&gt;Return a view onto the collection of TaskCompletionSource&amp;lt;T&amp;gt; values, projecting each one to its Task property &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Once you&amp;#39;re happy with the idea, the implementation isn&amp;#39;t too surprising (although it &lt;em&gt;is&lt;/em&gt; quite long):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Returns a sequence of tasks which will be observed to complete with the same set&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// of results as the given input tasks, but in the order in which the original tasks complete.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; OrderByCompletion&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; inputTasks)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Copy the input so we know it&amp;#39;ll be stable, and we don&amp;#39;t evaluate it twice&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; inputTaskList = inputTasks.ToList();     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Could use Enumerable.Range here, if we wanted...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; completionSourceList = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;TaskCompletionSource&amp;lt;T&amp;gt;&amp;gt;(inputTaskList.Count);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0; i &amp;lt; inputTaskList.Count; i++)     &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; completionSourceList.Add(&lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;());     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// At any one time, this is &amp;quot;the index of the box we&amp;#39;ve just filled&amp;quot;.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// It would be nice to make it nextIndex and start with 0, but Interlocked.Increment&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// returns the incremented value...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; prevIndex = -1;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// We don&amp;#39;t have to create this outside the loop, but it makes it clearer&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// that the continuation is the same for all tasks.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Action&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; continuation = completedTask =&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;span class="ValueType"&gt;int&lt;/span&gt; index = Interlocked.Increment(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; prevIndex);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; source = completionSourceList[index];     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; PropagateResult(completedTask, source);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; inputTask &lt;span class="Statement"&gt;in&lt;/span&gt; inputTaskList)     &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;span class="InlineComment"&gt;// TODO: Work out whether TaskScheduler.Default is really the right one to use.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; inputTask.ContinueWith(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;&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; CancellationToken.None,     &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;&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;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskScheduler.Default);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; completionSourceList.Select(source =&amp;gt; source.Task);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Propagates the status of the given task (which must be completed) to a task completion source&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// (which should not be).&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; PropagateResult&amp;lt;T&amp;gt;(Task&amp;lt;T&amp;gt; completedTask,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; TaskCompletionSource&amp;lt;T&amp;gt; completionSource)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;switch&lt;/span&gt; (completedTask.Status)     &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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Canceled:     &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; completionSource.TrySetCanceled();     &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;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Faulted:     &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; completionSource.TrySetException(completedTask.Exception.InnerExceptions);     &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;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.RanToCompletion:     &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; completionSource.TrySetResult(completedTask.Result);     &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;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;default&lt;/span&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;span class="InlineComment"&gt;// TODO: Work out whether this is really appropriate. Could set&lt;/span&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;span class="InlineComment"&gt;// an exception in the completion source, of course...&lt;/span&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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException(&lt;span class="String"&gt;&amp;quot;Task was not completed&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;You&amp;#39;ll notice there are a couple of TODO comments there. The exception in PropagateResult really &lt;em&gt;shouldn&amp;#39;t&lt;/em&gt; happen - the continuation shouldn&amp;#39;t be called when the task hasn&amp;#39;t completed. I still need to think carefully about how tasks should propagate exceptions though.&lt;/p&gt;  &lt;p&gt;The arguments to ContinueWith are more tricky: working through my TimeMachine class and some unit tests with Bill Wagner last week showed just how little I know about how SynchronizationContext, the task awaiters, task schedulers, and TaskContinuationOptions.ExecuteSynchronously all interact. I would &lt;em&gt;definitely&lt;/em&gt; need to look into that more deeply before TimeMachine was really ready for heavy use... which means &lt;em&gt;you&lt;/em&gt; should probably be looking at the TPL in more depth too.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Sure enough, when you run the code, the results appear in order, as the tasks complete. Here&amp;#39;s one sample of the output:&lt;/p&gt;  &lt;div class="code"&gt;Initial order: 335 468 1842 1991 2512 2603 270 2854 1972 1327   &lt;br /&gt;In order of completion:    &lt;br /&gt;270    &lt;br /&gt;335    &lt;br /&gt;468    &lt;br /&gt;1327    &lt;br /&gt;1842    &lt;br /&gt;1972    &lt;br /&gt;1991    &lt;br /&gt;2512    &lt;br /&gt;2603    &lt;br /&gt;2854 &lt;/div&gt;  &lt;p&gt;TODOs aside, the code in this post is remarkable (which I can say with modesty, as I&amp;#39;ve only refactored it from the code sent to me by another reader and Stephen Toub). It makes me smile every time I &lt;em&gt;think&lt;/em&gt; about the seemingly-impossible job it accomplishes. I suspect this approach could be useful in any number of composition blocks - it&amp;#39;s definitely one to remember.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1804970" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 18: Changes between the Async CTP and the Visual Studio 11 Preview</title><link>http://msmvps.com/blogs/jon_skeet/archive/2012/01/12/eduasync-part-18-changes-between-the-async-ctp-and-the-visual-studio-11-preview.aspx</link><pubDate>Thu, 12 Jan 2012 01:34:31 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1804610</guid><dc:creator>skeet</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1804610</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1804610</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/12/eduasync-part-18-changes-between-the-async-ctp-and-the-visual-studio-11-preview.aspx#comments</comments><description>&lt;p&gt;In preparation for CodeMash, I&amp;#39;ve been writing some more async code and decompiling it with Reflector. This time I&amp;#39;m using the Visual Studio 11 Developer Preview - the version which installs alongside Visual Studio 2010 under Windows 7. (Don&amp;#39;t ask me about any other features of Visual Studio 11 - I haven&amp;#39;t explored it thoroughly; I&amp;#39;ve really only used it for the C# 5 bits.)&lt;/p&gt;  &lt;p&gt;There have been quite a few changes since the CTP - they&amp;#39;re not &lt;em&gt;visible&lt;/em&gt; changes in terms of code that you&amp;#39;d normally write, but the state machine generated by the C# compiler is reasonably different. In this post I&amp;#39;ll describe the differences, as best I understand them. There are still a couple of things I don&amp;#39;t understand (which I&amp;#39;ll highlight within the post) but overall, I think I&amp;#39;ve got a pretty good handle on why the changes have been made.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m going to assume you already have a &lt;em&gt;reasonable&lt;/em&gt; grasp of the basic idea of async and how it works - the way that the compiler generates a state machine to represent an async method or anonymous function, with originally-local variables being promoted to instance variables within the state machine, etc. If the last sentence was a complete mystery to you, see &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-7-generated-code-from-a-simple-async-method.aspx"&gt;Eduasync part 7&lt;/a&gt; for more information. I don&amp;#39;t expect you to remember the &lt;em&gt;exact&lt;/em&gt; details of what was in the previous CTP though :)&lt;/p&gt;  &lt;h2&gt;Removal of iterator block leftovers&lt;/h2&gt;  &lt;p&gt;In the CTP, the code for async methods was based on the iterator block implementation. I suspect that&amp;#39;s still the case, but possibly sharing just a little less code. There used to be a few methods and fields which weren&amp;#39;t used in async methods, but now they&amp;#39;re gone:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;There&amp;#39;s no now constructor, so no need for the &amp;quot;skeleton&amp;quot; method which replaces the real async method to pass in 0 as the initial state. &lt;/li&gt;    &lt;li&gt;There&amp;#39;s no Dispose method. &lt;/li&gt;    &lt;li&gt;There&amp;#39;s no disposing field. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It&amp;#39;s nice to see these gone, but it&amp;#39;s not terribly interesting. Now on to the bigger changes...&lt;/p&gt;  &lt;h2&gt;Large structural changes&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s a set of related structural changes which don&amp;#39;t make sense individually. I&amp;#39;ll describe them first, then look at how it all hangs together, and my guess as to the reasoning behind.&lt;/p&gt;  &lt;h3&gt;The state machine is now a struct&lt;/h3&gt;  &lt;p&gt;The declaration of the nested type for the state machine is now something like this:&lt;/p&gt;  &lt;div class="code"&gt;[CompilerGenerated]    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; StateMachine : IStateMachine     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Fields common to all async state machines&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// (with caveats)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; state;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; awaiter;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; builder;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Action moveNextDelegate;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; stack;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Hoisted local variables&lt;/span&gt;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Methods&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [DebuggerHidden]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetMoveNextDelegate(Action action) { ... }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; MoveNext() { ... }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The caveats around the common field are in terms of the return type of the async method (which determines the type of builder used) and whether or not there are any awaits (if there are no awaits, the stack and awaiter fields aren&amp;#39;t generated).&lt;/p&gt;  &lt;p&gt;Note that throughout this blog post I&amp;#39;ve changed the names of fields and types - in reality they&amp;#39;re all &amp;quot;unspeakable&amp;quot; names including angle-brackets, just like all compiler-generated names.&lt;/p&gt;  &lt;h3&gt;There&amp;#39;s a new assembly-wide interface&lt;/h3&gt;  &lt;p&gt;As you can see from the code above, the state machine implements an interface (actually called &amp;lt;&amp;gt;t__IStateMachine). One of these is created in the global namespace in each assembly that contains at least one async method or anonymous function, and it looks like this:&lt;/p&gt;  &lt;div class="code"&gt;[CompilerGenerated]    &lt;br /&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IStateMachine     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;void&lt;/span&gt; SetMoveNextDelegate(Action action);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The implementation for this method is always the same, and it&amp;#39;s trivial:&lt;/p&gt;  &lt;div class="code"&gt;[DebuggerHidden]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetMoveNextDelegate(Action action)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.moveNextDelegate = action;     &lt;br /&gt;} &lt;/div&gt;  &lt;h3&gt;Simplified skeleton method&lt;/h3&gt;  &lt;p&gt;The method which starts the state machine, which I&amp;#39;ve been calling the &amp;quot;skeleton&amp;quot; method everywhere, is now a bit simpler than it was. Something like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; FooAsync()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; StateMachine machine = &lt;span class="Keyword"&gt;new&lt;/span&gt; StateMachine();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; machine.builder = AsyncVoidMethodBuilder.Create();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; machine.MoveNext();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; machine.builder.Task;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;In fact if you decompile the IL, you&amp;#39;ll see that it &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; explicitly initialize the variable to start with - it just declares it, sets the builder field and then calls MoveNext(). That&amp;#39;s not valid C# (as all the struct&amp;#39;s fields aren&amp;#39;t initialized), but it &lt;em&gt;is&lt;/em&gt; valid IL. It&amp;#39;s &lt;em&gt;equivalent&lt;/em&gt; to the code above though. Note how there&amp;#39;s nothing to set the continuation - where previously the moveNextDelegate field would be populated within the skeleton method.&lt;/p&gt;  &lt;h3&gt;Just-in-time delegate creation&lt;/h3&gt;  &lt;p&gt;Now that the skeleton method doesn&amp;#39;t create the delegate representing the continuation, it can be done when it&amp;#39;s first required - which is when we first encounter an await expression for an awaitable which hasn&amp;#39;t already completed. (If the awaitable has completed before we await it, the generated code skips the continuation and just uses the results immediately and synchronously).&lt;/p&gt;  &lt;p&gt;The code for that delegate creation is slightly trickier than you might expect, however. It looks something like this:&lt;/p&gt;  &lt;div class="code"&gt;Action action = &lt;span class="Keyword"&gt;this&lt;/span&gt;.moveNextDelegate;     &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (action == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = &lt;span class="Keyword"&gt;this&lt;/span&gt;.builder.Task;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; action = &lt;span class="Keyword"&gt;new&lt;/span&gt; Action(&lt;span class="Keyword"&gt;this&lt;/span&gt;.MoveNext);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ((IStateMachine) action.Target).SetMoveNextDelegate(action);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;There are two oddities here, one of which I mostly understand and one of which I don&amp;#39;t understand at all.&lt;/p&gt;  &lt;p&gt;I really don&amp;#39;t understand the &amp;quot;task&amp;quot; variable here. Why do we need to exercise the AsyncTaskMethodBuilder.Task property? We don&amp;#39;t use the result anywhere... does forcing this flush some memory buffer? I have no clue on this one. &lt;strong&gt;(See the update at the bottom of the post...)&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The part about setting the delegate via the interface makes more sense, but it&amp;#39;s subtle. You might &lt;em&gt;expect&lt;/em&gt; code like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Looks sensible, but is actually slightly broken&lt;/span&gt;     &lt;br /&gt;Action action = &lt;span class="Keyword"&gt;this&lt;/span&gt;.moveNextDelegate;     &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (action == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; action = &lt;span class="Keyword"&gt;new&lt;/span&gt; Action(&lt;span class="Keyword"&gt;this&lt;/span&gt;.MoveNext);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.moveNextDelegate = action;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;That would &lt;em&gt;sort of&lt;/em&gt; work - but we&amp;#39;d end up needing to recreate the delegate each time we encountered an appropriate await expression. Although the above code saves the value to the field, it saves it within the current value of the state machine... &lt;em&gt;after&lt;/em&gt; we&amp;#39;ve boxed that value as the target of the delegate. The value we want to mutate is the one &lt;em&gt;within the box&lt;/em&gt; - which is precisely why there&amp;#39;s an interface, and why the code casts to it.&lt;/p&gt;  &lt;p&gt;We can&amp;#39;t even just unbox and then set the field afterwards - at least in C# - because the unbox operation is always followed by a copy operation in normal C#. I &lt;em&gt;believe&lt;/em&gt; it would be possible for the C# compiler to generate IL which unboxed action.Target &lt;em&gt;without&lt;/em&gt; the copy, and then set the field in that. It&amp;#39;s not clear to me why the team went with the interface approach instead... I would &lt;em&gt;expect&lt;/em&gt; that to be slower (as it requires dynamic dispatch) but I could easily be wrong. Of course, it would also make it impossible to decompile the IL to C#, which would make my talks harder, but don&amp;#39;t expect the C# team to bend the compiler implementation for my benefit ;)&lt;/p&gt;  &lt;p&gt;(As an aside to all of this, I&amp;#39;ve gone back and forth on whether the &amp;quot;slightly broken&amp;quot; implementation would recreate the delegate on &lt;em&gt;every&lt;/em&gt; appropriate await, or only two. I &lt;em&gt;think&lt;/em&gt; it would end up being on every occurrence, as even though on the second occurrence we&amp;#39;d be operating within the context of the first boxed instance, the new delegate would have a reference to a &lt;em&gt;new&lt;/em&gt; boxed copy each time. It does my head in a little bit, trying to think about this... more evidence that mutable structs are evil and hard to reason about. It&amp;#39;s not the wrong decision in this case, hidden far from the gaze of normal developers, but it&amp;#39;s a pain to reason about.)&lt;/p&gt;  &lt;h3&gt;Single awaiter variable&lt;/h3&gt;  &lt;p&gt;In the CTP, each await expression generated a separate field within the state machine, and that field was always of the exact awaiter type. In the VS11 Developer Preview, there&amp;#39;s always exactly &lt;em&gt;one&lt;/em&gt; awaiter field (assuming there&amp;#39;s at least one await expression) and it&amp;#39;s always of type object. It&amp;#39;s used like this:&lt;/p&gt;  &lt;div class="code"&gt;&amp;#160; &lt;span class="InlineComment"&gt;// Single local variable used by both continuation and first-time paths&lt;/span&gt;     &lt;br /&gt;&amp;#160; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; localAwaiter;     &lt;br /&gt;    &lt;br /&gt;&amp;#160; ...     &lt;br /&gt;    &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (conditions-&lt;span class="Statement"&gt;for&lt;/span&gt;-first-time-execution)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Code before await&lt;/span&gt;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; localAwaiter = task.GetAwaiter();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (localAwaiter.IsCompleted)     &lt;br /&gt;&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; &lt;span class="Statement"&gt;goto&lt;/span&gt; Await1Completed;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.state = 1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;[] awaiterArray = { localAwaiter };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.awaiter = awaiterArray;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Lazy delegate creation goes here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiterArray[0].OnCompleted(action);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; &lt;span class="InlineComment"&gt;// Continuation would get into here&lt;/span&gt;     &lt;br /&gt;&amp;#160; localAwaiter = ((TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;[]) &lt;span class="Keyword"&gt;this&lt;/span&gt;.awaiter)[0];     &lt;br /&gt;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.awaiter = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.state = 0;     &lt;br /&gt;Await1Completed:     &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; result = localAwaiter.GetResult();&amp;#160; &lt;br /&gt;&amp;#160; localA&lt;span class="ValueType"&gt;&lt;font color="#333333"&gt;waiter = &lt;/font&gt;&lt;span class="Modifier"&gt;default&lt;/span&gt;&lt;font color="#333333"&gt;(TaskAwaiter&amp;lt;&lt;/font&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&lt;font color="#333333"&gt;&amp;gt;);&lt;/font&gt;&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;I realize there&amp;#39;s a lot of code here, but it does make some sense:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The value of the awaiter field is always either null, or a reference to a single-element array of the awaiter type for one of the await expressions. &lt;/li&gt;    &lt;li&gt;A single localAwaiter variable is shared between the two code paths, populated either from the awaitable (on the initial code path) or by copying the value from the array (in the second code path). &lt;/li&gt;    &lt;li&gt;The field is always set to null and the local variable is set to its default value after use, presumably for the sake of garbage collection &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It&amp;#39;s basically a nice way of using the fact that we&amp;#39;ll only ever need one awaiter at a time. It&amp;#39;s not clear to me why an array is used instead of either using a reference to the awaiter for class-based awaiters, or simply by boxing for struct-based awaiters. The latter would need the same &amp;quot;unbox without copy&amp;quot; approach discussed in the previous section - so if there&amp;#39;s some reason why that&amp;#39;s actually infeasible, it would explain the use of an array here. We &lt;em&gt;can&amp;#39;t&lt;/em&gt; use the interface trick in this case, as the compiler isn&amp;#39;t in control of the awaiter type (so can&amp;#39;t make it implement an interface).&lt;/p&gt;  &lt;h3&gt;Expression stack preservation&lt;/h3&gt;  &lt;p&gt;This one is actually a fix to a bug in the async CTP, which I&amp;#39;ve &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/06/10/eduasync-part-10-ctp-bug-don-t-combine-multiple-awaits-in-one-statement.aspx"&gt;written about before&lt;/a&gt;. We&amp;#39;re used to the stack containing our local variables (in the absence of iterator blocks, captured variables etc, and modulo the stack being an implementation detail) but it&amp;#39;s also used for intermediate results within a single statement. For example, consider this block of code:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; x = 10;     &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; y = 5;     &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; z = x + 50 * y; &lt;/div&gt;  &lt;p&gt;That last line is effectively:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Load the value of x onto the stack &lt;/li&gt;    &lt;li&gt;Load the value 50 onto the stack &lt;/li&gt;    &lt;li&gt;Load the value of y onto the stack &lt;/li&gt;    &lt;li&gt;Multiply the top two stack values (50 and y) leaving the result on the stack &lt;/li&gt;    &lt;li&gt;Add the top two stack values (x and the previously-computed result) leaving the result on the stack &lt;/li&gt;    &lt;li&gt;Store the top stack value into z &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now suppose we want to turn y into a Task&amp;lt;int&amp;gt;:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; x = 10;     &lt;br /&gt;Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; y = Task.FromResult(5);     &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; z = x + 50 * &lt;span class="Modifier"&gt;await&lt;/span&gt; y; &lt;/div&gt;  &lt;p&gt;Our state machine needs to make sure that it will preserve the same behaviour as the synchronous version, so it needs the same sort of stack. In the new-style state machine, all of that stack is saved in the &amp;quot;stack&amp;quot; field. It&amp;#39;s only one field, but may need to represent multiple different types within the code at various different await expressions - in the code above, for example, it represents two int values. As far as I can discover, the C# compiler generates code which uses the actual type of the value it needs, if it only requires a single value. If it needs multiple values, it uses an appropriate Tuple type, nesting tuples if it goes beyond the number of type parameters supported by the Tuple&amp;lt;...&amp;gt; family of types. So in our case above, we end up with code a &lt;em&gt;bit&lt;/em&gt; like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Local variable used in both paths&lt;/span&gt;     &lt;br /&gt;Tuple&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; tuple;     &lt;br /&gt;    &lt;br /&gt;...     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Code before the await&lt;/span&gt;     &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (conditions-&lt;span class="Statement"&gt;for&lt;/span&gt;-first-time-execution)&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; tuple = &lt;span class="Keyword"&gt;new&lt;/span&gt; Tuple&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt;.x, 50);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.stack = tuple;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ...     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Continuation would get into here&lt;/span&gt;     &lt;br /&gt;tuple = (Tuple&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;) &lt;span class="Keyword"&gt;this&lt;/span&gt;.stack;     &lt;br /&gt;&lt;span class="InlineComment"&gt;// IL copies the values from the tuple onto the stack at this point&lt;/span&gt;     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.stack = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;    &lt;br /&gt;...     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Both the fast and slow code paths get here eventually&lt;/span&gt;     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.z = stack0 + stack1 * awaiter.GetResult() &lt;/div&gt;  &lt;p&gt;I say it&amp;#39;s a &lt;em&gt;bit&lt;/em&gt; like this, because it&amp;#39;s hard to represent the IL exactly in C# in this case. The tuple is only created if it&amp;#39;s needed, i.e. not in the already-completed fast path. In that case, the values are loaded onto the stack but &lt;em&gt;not&lt;/em&gt; then put into the tuple - execution skips straight to the code which uses the values already on the stack.&lt;/p&gt;  &lt;p&gt;When the awaitable &lt;em&gt;isn&amp;#39;t&lt;/em&gt; complete immediately, then a Tuple&amp;lt;int, int&amp;gt; is created, stored in the &amp;quot;stack&amp;quot; field, and the continuation is handed to the awaiter. On continuation, the tuple is loaded back from the &amp;quot;stack&amp;quot; field (and cast accordingly), the values are loaded onto the stack - and then we&amp;#39;re back into the common code path of fetching the value and performing the add and multiply operations.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;As far as I&amp;#39;m aware, those are the most noticeable changes in the generated code. There may well still be a load more changes in Task&amp;lt;T&amp;gt; and the TPL in general - I wouldn&amp;#39;t be at all surprised - but that&amp;#39;s harder to investigate.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m sure all of this has been done in the name of performance (and correctness, in the case of stack preservation). The state machine is now much smaller in terms of the number of fields it requires, and objects are created locally as far as possible (including the state machine itself only requiring heap allocation if there&amp;#39;s ever a &amp;quot;slow&amp;quot; awaitable). I suspect there&amp;#39;s still some room for optimization, however:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Both the awaiter and the delegate use careful boxing and either arrays or a mutating interface to allow the boxed value to be changed. I suspect that using unbox with the concrete type, but without copying the value, would be more efficient. I may attempt to work this theory up into a test at some point. &lt;/li&gt;    &lt;li&gt;If there&amp;#39;s only one awaiter type (usually TaskAwaiter&amp;lt;T&amp;gt; for some T), that type could be used instead of object, potentially reducing heap optimization &lt;/li&gt;    &lt;li&gt;I&amp;#39;ve no idea why the builder.Task property is explicitly fetched and then the results discarded&lt;/li&gt;    &lt;li&gt;If there&amp;#39;s only one await expression, the &amp;quot;stack&amp;quot; field can be strongly typed, which would also avoid boxing if only a single value needs to be within that stack &lt;/li&gt;    &lt;li&gt;The stack field could be removed entirely when it&amp;#39;s not needed for intermediate stack value preservation. (I believe that would be the case reasonably often.) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The use of mutable value types is really fascinating (for me, at least) - I&amp;#39;m sure most people on the C# team would still say they&amp;#39;re evil, but when they&amp;#39;re used in a carefully controlled environment where real developers don&amp;#39;t have to reason about their behaviour, they can be useful.&lt;/p&gt;  &lt;p&gt;Next time, I&amp;#39;ll hopefully get back to the idea I promised to write up before, about ordering a collection of tasks in completion order... before they&amp;#39;ve completed. (Well, sort of.) Should be fun...&lt;/p&gt;  &lt;h2&gt;Update (January 16th 2012)&lt;/h2&gt;  &lt;p&gt;Stephen Toub got in touch with me after I posted the original version of this blog entry, to explain the use of the Task property. Apparently the idea is that at this point, we &lt;em&gt;know&lt;/em&gt; we&amp;#39;re going to return out of the state machine, so the skeleton method is going to access the Task property anyway. However, as we haven&amp;#39;t scheduled the continuation yet we &lt;em&gt;also&lt;/em&gt; know that nothing will be accessing the Task property on a different thread. If we access it now for the first time, we can lazily allocate the task &lt;em&gt;in the same thread that created the AsyncMethodBuilder, with no risk of contention.&lt;/em&gt; If we can force there to be a task ready and waiting for whatever accesses it later, we don&amp;#39;t need any synchronization in that area.&lt;/p&gt;  &lt;p&gt;So why might we want to allocate the task lazily in the first place? Well, don&amp;#39;t forget that we might &lt;em&gt;never&lt;/em&gt; have to wait for an await (as it were). We might just have an async method which takes the fast path everywhere. If that&amp;#39;s the case, then for certain cases (e.g. a non-generic, successfully completed task, or a Task&amp;lt;bool&amp;gt; which again has completed successfully) we can reuse the same instance repeatedly. Apparently this laziness isn&amp;#39;t yet part of the VS11 Developer Preview, but the reason for the property access is in preparation for this.&lt;/p&gt;  &lt;p&gt;Another case of micro-optimization - which is fair enough when it&amp;#39;s at a system level :)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1804610" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 17: unit testing</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/11/25/eduasync-part-17-unit-testing.aspx</link><pubDate>Fri, 25 Nov 2011 21:46:45 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1802928</guid><dc:creator>skeet</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1802928</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1802928</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/11/25/eduasync-part-17-unit-testing.aspx#comments</comments><description>&lt;p&gt;In the &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/11/22/eduasync-part-16-example-of-composition-majority-voting.aspx"&gt;last post&lt;/a&gt; I showed a method to implement &amp;quot;majority voting&amp;quot; for tasks, allowing a result to become available as soon as possible. At the end, I mentioned that I was reasonably confident that it worked because of the unit tests... but I didn&amp;#39;t show the tests themselves. I felt they deserved their own post, as there&amp;#39;s a bigger point here: &lt;em&gt;it&amp;#39;s possible to unit test async code&lt;/em&gt;. At least sometimes.&lt;/p&gt;  &lt;p&gt;Testing code involving asynchrony is generally a pain. Introducing the exact order of events that you want is awkward, as is managing the threading within tests. With a few benefits with async methods:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We know that the async method itself will only execute in a single thread at a time &lt;/li&gt;    &lt;li&gt;We can control the thread in which the async method will execute, &lt;em&gt;if&lt;/em&gt; it doesn&amp;#39;t configure its awaits explicitly &lt;/li&gt;    &lt;li&gt;Assuming the async method returns Task or Task&amp;lt;T&amp;gt;, we can check whether or not it&amp;#39;s finished &lt;/li&gt;    &lt;li&gt;Between Task&amp;lt;T&amp;gt; and TaskCompletionSource&amp;lt;T&amp;gt;, we have a way of injecting tasks that we understand &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now in our sample method we have the benefit of passing in the tasks that will be awaited - but assuming you&amp;#39;re using some reasonably testable API to fetch any awaitables within your async method, you should be okay. (Admittedly in the current .NET framework that excludes rather a lot of classes... but the synchronous versions of those calls are also generally hard to test too.)&lt;/p&gt;  &lt;h3&gt;The plan&lt;/h3&gt;  &lt;p&gt;For our majority tests, we want to be able to see what happens in various scenarios, with tasks completing at different times and in different ways. Looking at the &lt;a href="http://code.google.com/p/eduasync/source/browse/src/MajorityVoting.Tests/WhenMajorityTest.cs"&gt;test cases I&amp;#39;ve implemented&lt;/a&gt; I have the following tests:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;NullSequenceOfTasks &lt;/li&gt;    &lt;li&gt;EmptySequenceOfTasks &lt;/li&gt;    &lt;li&gt;NullReferencesWithinSequence &lt;/li&gt;    &lt;li&gt;SimpleSuccess &lt;/li&gt;    &lt;li&gt;InputOrderIsIrrelevant &lt;/li&gt;    &lt;li&gt;MajorityWithSomeDisagreement &lt;/li&gt;    &lt;li&gt;MajorityWithFailureTask &lt;/li&gt;    &lt;li&gt;EarlyFailure &lt;/li&gt;    &lt;li&gt;NoMajority &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;m not going to claim this is a &lt;em&gt;comprehensive&lt;/em&gt; set of possible tests - it&amp;#39;s a proof of concept more than anything else. Let&amp;#39;s take one test as an example: MajorityWithFailureTask. The aim of this is to pass three tasks (of type Task&amp;lt;string&amp;gt;) into the method. One will give a result of &amp;quot;x&amp;quot;, the second will fail with an exception, and the third will also give a result of &amp;quot;x&amp;quot;. The events will occur in that order, and only when all three results are in should the returned task complete, at which point it will also have a success result of &amp;quot;x&amp;quot;.&lt;/p&gt;  &lt;p&gt;So, the tricky bit (compared with normal testing) is introducing the timing. We want to make it &lt;em&gt;appear&lt;/em&gt; as if tasks are completing in a particular order, at predetermined times, so we can check the state of the result between events.&lt;/p&gt;  &lt;h3&gt;Introducing the TimeMachine class&lt;/h3&gt;  &lt;p&gt;Okay, so it&amp;#39;s a silly name. But the basic idea is to have something to control the logical flow of time through our test. We&amp;#39;re going to ask the TimeMachine to &lt;em&gt;provide&lt;/em&gt; us with tasks which will act in a particular way at a given time, and then when we&amp;#39;ve started our async method we can then ask it to move time forward, letting the tasks complete as they go. It&amp;#39;s probably best to look at the code for MajorityWithFailureTask first, and then see what the implementation of TimeMachine looks like. Here&amp;#39;s the test:&lt;/p&gt;  &lt;div class="code"&gt;[Test]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; MajorityWithFailureTask()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; timeMachine = &lt;span class="Keyword"&gt;new&lt;/span&gt; TimeMachine();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Second task gives a different result&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; task1 = timeMachine.AddSuccessTask(1, &lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; task2 = timeMachine.AddFaultingTask&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;(2, &lt;span class="Keyword"&gt;new&lt;/span&gt; Exception(&lt;span class="String"&gt;&amp;quot;Bang!&amp;quot;&lt;/span&gt;));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; task3 = timeMachine.AddSuccessTask(3, &lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; resultTask = MoreTaskEx.WhenMajority(task1, task2, task3);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Assert.IsFalse(resultTask.IsCompleted);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Only one result so far - no consensus&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; timeMachine.AdvanceTo(1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Assert.IsFalse(resultTask.IsCompleted);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Second result is a failure&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; timeMachine.AdvanceTo(2);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Assert.IsFalse(resultTask.IsCompleted);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Third result gives majority verdict&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; timeMachine.AdvanceTo(3);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Assert.AreEqual(TaskStatus.RanToCompletion, resultTask.Status);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Assert.AreEqual(&lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;, resultTask.Result);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;As you can see, there are two types of method:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;AddSuccessTask / AddFaultingTask / AddCancelTask (not used here) - these all take the time at which they&amp;#39;re going to complete as their first parameter, and the method name describes the state they&amp;#39;ll reach on completion. The methods &lt;em&gt;return&lt;/em&gt; the task created by the time machine, ready to pass into the production code we&amp;#39;re testing. &lt;/li&gt;    &lt;li&gt;AdvanceTo / AdvanceBy (not used here) - make the time machine &amp;quot;advance time&amp;quot;, completing pre-programmed tasks as it goes. When those tasks complete, any continuations attached to them also execute, which is how the whole thing hangs together. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now forcing tasks to complete is actually pretty simple, if you build them out of TaskCompletionSource&amp;lt;T&amp;gt; to start with. So all we need to do is keep our tasks in &amp;quot;time&amp;quot; order (which I achieve with SortedList), and then when we&amp;#39;re asked to advance time we move through the list and take the appropriate action for all the tasks which &lt;em&gt;weren&amp;#39;t&lt;/em&gt; completed before, but are now. I represent the &amp;quot;appropriate action&amp;quot; as a simple Action, which is built with a lambda expression from each of the Add methods. It&amp;#39;s really simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TimeMachine    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; currentTime = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; SortedList&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, Action&amp;gt; actions = &lt;span class="Keyword"&gt;new&lt;/span&gt; SortedList&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, Action&amp;gt;();    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; CurrentTime { get { &lt;span class="Statement"&gt;return&lt;/span&gt; currentTime; } }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; AdvanceBy(&lt;span class="ValueType"&gt;int&lt;/span&gt; time)    &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; AdvanceTo(currentTime + time);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; AdvanceTo(&lt;span class="ValueType"&gt;int&lt;/span&gt; time)    &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;span class="InlineComment"&gt;// Okay, not terribly efficient, but it&amp;#39;s simple.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; entry &lt;span class="Statement"&gt;in&lt;/span&gt; actions)    &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;span class="Statement"&gt;if&lt;/span&gt; (entry.Key &amp;gt; currentTime &amp;amp;&amp;amp; entry.Key &amp;lt;= time)    &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; entry.Value();    &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; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; currentTime = time;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; AddSuccessTask&amp;lt;T&amp;gt;(&lt;span class="ValueType"&gt;int&lt;/span&gt; time, T result)    &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; TaskCompletionSource&amp;lt;T&amp;gt; tcs = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; actions[time] = () =&amp;gt; tcs.SetResult(result);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; tcs.Task;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; AddCancelTask&amp;lt;T&amp;gt;(&lt;span class="ValueType"&gt;int&lt;/span&gt; time)    &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; TaskCompletionSource&amp;lt;T&amp;gt; tcs = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; actions[time] = () =&amp;gt; tcs.SetCanceled();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; tcs.Task;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; AddFaultingTask&amp;lt;T&amp;gt;(&lt;span class="ValueType"&gt;int&lt;/span&gt; time, Exception e)    &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; TaskCompletionSource&amp;lt;T&amp;gt; tcs = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; actions[time] = () =&amp;gt; tcs.SetException(e);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; tcs.Task;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Okay, that&amp;#39;s a fair amount of code for a blog posts (and yes, it could do with some doc comments etc!) but considering that it makes life testable, it&amp;#39;s pretty simple.&lt;/p&gt;  &lt;p&gt;So, is that it?&lt;/p&gt;  &lt;h3&gt;It works on my machine... with my test runner... in simple cases...&lt;/h3&gt;  &lt;p&gt;When I first ran the tests using TimeMachine, they worked almost immediately. This didn&amp;#39;t surprise me nearly as much as it should have done. You see, when the tests execute, they use async/await in the normal way - which means the continuations are scheduled on &amp;quot;the current task scheduler&amp;quot;. &lt;em&gt;I have no idea what the current task scheduler is in unit tests&lt;/em&gt;. Or rather, it feels like something which is implementation specific. It could easily have worked when running the tests from ReSharper, but not from NCrunch, or not from the command line NUnit test runner.&lt;/p&gt;  &lt;p&gt;As it happens, I believe all of these run tests on thread pool threads with no task scheduler allocated, which means that the continuation is attached to the task to complete &amp;quot;in-line&amp;quot; - so when the TimeMachine sets the result on a TaskCompletionSource, the continuations execute before that call returns. That means everything happens on one thread, with no ambiguity or flakiness - yay!&lt;/p&gt;  &lt;p&gt;However, there are two problems:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The words &amp;quot;I believe&amp;quot; aren&amp;#39;t exactly confidence-inspiring when it comes to testing that your software works correctly.&lt;/li&gt;    &lt;li&gt;Our majority voting code only ever sees one completed task at a time - we&amp;#39;re not testing the situation where several tasks complete so quickly together that the continuation doesn&amp;#39;t get chance to run before they&amp;#39;ve all finished.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Both of these are solvable with a custom TaskScheduler or SynchronizationContext. Without diving into the docs, I&amp;#39;m not sure yet which I&amp;#39;ll need, but the aim will be:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Make TimeMachine implement IDisposable&lt;/li&gt;    &lt;li&gt;In the constructor, set the current SynchronizationContext (or TaskScheduler) to a custom one having remembered what the previous one was&lt;/li&gt;    &lt;li&gt;On disposal, reset the context&lt;/li&gt;    &lt;li&gt;Make the custom scheduler keep a queue of jobs, such that when we&amp;#39;re asked to advance to time T, we complete &lt;em&gt;all&lt;/em&gt; the appropriate tasks but don&amp;#39;t execute any continuations, then we execute all the pending continuations.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I don&amp;#39;t yet know how hard it will be, but hopefully the &lt;a href="http://code.msdn.microsoft.com/ParExtSamples"&gt;Parallel Extensions Samples&lt;/a&gt; will help me.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;I&amp;#39;m not going to claim this is &amp;quot;the&amp;quot; way of unit testing asynchronous methods. It&amp;#39;s clearly a proof-of-concept implementation of what can only be called a &amp;quot;test framework&amp;quot; in the loosest possible sense. However, I hope it gives &lt;em&gt;an&lt;/em&gt; example of a path we might take. I&amp;#39;m looking forward to seeing what others come up with, along with rather more polished implementations.&lt;/p&gt;  &lt;p&gt;Next time, I&amp;#39;m going to shamelessly steal an idea that a reader mailed me (with permission, of course). It&amp;#39;s insanely cool, simple and yet slightly brain-bending, and I suspect will handy in many situations. Love it.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1802928" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 16: Example of composition: majority voting</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/11/22/eduasync-part-16-example-of-composition-majority-voting.aspx</link><pubDate>Tue, 22 Nov 2011 23:18:41 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1802817</guid><dc:creator>skeet</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1802817</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1802817</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/11/22/eduasync-part-16-example-of-composition-majority-voting.aspx#comments</comments><description>&lt;p&gt;Note: For the rest of this series, I&amp;#39;ll be veering away from the original purpose of the project (investigating what the compiler is up to) in favour of discussing the feature itself. As such, I&amp;#39;ve added a requirement for AsyncCtpLib.dll - but due to potential distribution restrictions, I&amp;#39;ve felt it safest &lt;em&gt;not&lt;/em&gt; to include that in the source repository. If you&amp;#39;re running this code yourself, you&amp;#39;ll need to copy the DLL from your installation location into the Eduasync\lib directory before it will build - or change each reference to it.&lt;/p&gt;  &lt;p&gt;One of the things I &lt;em&gt;love&lt;/em&gt; about async is the compositional aspect. This is partly due to the way that the Task Parallel Library encourages composition to start with, but async/await makes it even easier by building the tasks for you. In the next few posts I&amp;#39;ll talk about a few examples of interesting building blocks. I wouldn&amp;#39;t be surprised to see an open source library with a &lt;em&gt;proper&lt;/em&gt; implementation of some of these ideas (Eduasync is &lt;em&gt;not&lt;/em&gt; designed for production usage) whether from Microsoft or a third party.&lt;/p&gt;  &lt;p&gt;In &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FMajorityVoting"&gt;project 26 of Eduasync&lt;/a&gt;, I&amp;#39;ve implemented &amp;quot;majority voting&amp;quot; via composition. The basic idea is simple, and the motivation should be reasonably obvious in this day and age of redundant services. You have (say) five different tasks which are meant to be computing the same thing. As soon as you have a single answer which the majority of the tasks agree on, the code which needs the result can continue. If the tasks disagree, or fail (or a combination leading to no single successful majority result), the overall result is failure too.&lt;/p&gt;  &lt;p&gt;My personal experience with services requiring a majority of operations to return is with &lt;a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en//pubs/archive/36971.pdf"&gt;Megastore&lt;/a&gt;, a storage system we use at Google. I&amp;#39;m not going to pretend to understand half of the details of how Megastore works, and I&amp;#39;m certainly not about to reveal any confidential information about its internals or indeed how we use it, but basically when discussing it with colleagues at around the time that async was announced, I contemplated what a handy feature async would be when implementing a Megastore client. It could also be used in systems where each calculation is performed in triplicate to guard against rogue errors - although I suspect the chances of those systems being implemented in C# are pretty small.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s worth mentioning that the implementation here &lt;em&gt;wouldn&amp;#39;t&lt;/em&gt; be appropriate for something like a stock price service, where the result can change rapidly and you may be happy to tolerate a &lt;em&gt;small&lt;/em&gt; discrepancy, within some bounds.&lt;/p&gt;  &lt;h3&gt;The API&lt;/h3&gt;  &lt;p&gt;Here&amp;#39;s the signatures of the methods we&amp;#39;ll implement:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WhenMajority&amp;lt;T&amp;gt;(&lt;span class="MethodParameter"&gt;params&lt;/span&gt; Task&amp;lt;T&amp;gt;[] tasks)     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WhenMajority&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; tasks) &lt;/div&gt;  &lt;p&gt;Obviously the first just delegates to the second, but it&amp;#39;s helpful to have both forms, so that we can pass in a few tasks in an ad hoc manner with the first overload, or a LINQ-generated sequence of tasks with the second.&lt;/p&gt;  &lt;p&gt;The name is a little odd - it&amp;#39;s meant to match WhenAll and WhenAny, but I&amp;#39;m sure there are better options. I&amp;#39;m not terribly interested in that at the moment.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s easy to use within an async method:&lt;/p&gt;  &lt;div class="code"&gt;Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; firstTask = firstServer.ComputeSomethingAsync(input);     &lt;br /&gt;Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; secondTask = selectServer.ComputeSomethingAsync(input);     &lt;br /&gt;Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; thirdTask = thirdServer.ComputeSomethingAsync(input);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; result = &lt;span class="Modifier"&gt;await&lt;/span&gt; MoreTaskEx.WhenMajority(firstTask, secondTask, thirdTask); &lt;/div&gt;  &lt;p&gt;Or using the LINQ-oriented overload:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; tasks = servers.Select(server =&amp;gt; server.ComputeSomethingAsync(input));     &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; result = &lt;span class="Modifier"&gt;await&lt;/span&gt; MoreTaskEx.WhenMajority(tasks); &lt;/div&gt;  &lt;p&gt;Of course we could add an extension method (dropping the When prefix as it doesn&amp;#39;t make as much sense there, IMO):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; result = &lt;span class="Modifier"&gt;await&lt;/span&gt; servers.Select(server =&amp;gt; server.ComputeSomethingAsync(input))     &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .MajorityAsync(); &lt;/div&gt;  &lt;p&gt;The fact that we&amp;#39;ve stayed within the Task&amp;lt;T&amp;gt; model is what makes it all work so smoothly. We couldn&amp;#39;t easily express the same API for other awaitable types &lt;em&gt;in general&lt;/em&gt; although we could do it for any other &lt;em&gt;specific&lt;/em&gt; awaitable type of course. It&amp;#39;s possible that it would work using dynamic, but I&amp;#39;d rather avoid that :) Let&amp;#39;s implement it now.&lt;/p&gt;  &lt;h3&gt;Implementation&lt;/h3&gt;  &lt;p&gt;There are two parts to the implementation, in the same way that we implemented LINQ operators in &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx"&gt;Edulinq&lt;/a&gt; - and for the same reason. We want to go bang &lt;em&gt;immediately&lt;/em&gt; if there are any clear input violations - such as the sequence of tasks being null or empty. This is in line with the &lt;a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;amp;id=19957"&gt;Task-based Asynchronous Pattern white paper&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;An asynchronous method should only directly raise an exception to be thrown out of the &lt;i&gt;MethodName&lt;/i&gt;Async call in response to a &lt;i&gt;usage&lt;/i&gt; error*. For all other errors, exceptions occurring during the execution of an asynchronous method should be assigned to the returned Task. &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now it occurs to me that we don&amp;#39;t &lt;em&gt;really&lt;/em&gt; need to do this in two separate methods (one for precondition checking, one for real work). We &lt;em&gt;could&lt;/em&gt; create an async lambda expression of type Func&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt;, and make the method just return the result of invoking it - but I don&amp;#39;t think that would be great in terms of readability.&lt;/p&gt;  &lt;p&gt;So, the first part of the implementation performing validation is really simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WhenMajority&amp;lt;T&amp;gt;(&lt;span class="MethodParameter"&gt;params&lt;/span&gt; Task&amp;lt;T&amp;gt;[] tasks)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; WhenMajority((IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt;) tasks);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WhenMajority&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; tasks)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (tasks == &lt;span class="Keyword"&gt;null&lt;/span&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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="String"&gt;&amp;quot;tasks&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; List&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; taskList = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt;(tasks);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (taskList.Count == 0)     &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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException(&lt;span class="String"&gt;&amp;quot;Empty sequence of tasks&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; task &lt;span class="Statement"&gt;in&lt;/span&gt; taskList)     &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;span class="Statement"&gt;if&lt;/span&gt; (task == &lt;span class="Keyword"&gt;null&lt;/span&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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException(&lt;span class="String"&gt;&amp;quot;Null task in sequence&amp;quot;&lt;/span&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; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; WhenMajorityImpl(taskList);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The interesting part is obviously in WhenMajorityImpl. It&amp;#39;s &lt;em&gt;mildly&lt;/em&gt; interesting to note that I create a copy of the sequence passed in to start with - I know I&amp;#39;ll need it in a fairly concrete form, so it&amp;#39;s appropriate to remove any laziness at this point.&lt;/p&gt;  &lt;p&gt;So, here&amp;#39;s WhenMajorityImpl, which I&amp;#39;ll then explain:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;T&amp;gt; WhenMajorityImpl&amp;lt;T&amp;gt;(List&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; tasks)    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Need a real majority - so for 4 or 5 tasks, must have 3 equal results.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; majority = (tasks.Count / 2) + 1;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; failures = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; bestCount = 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; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Dictionary&amp;lt;T, &lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; results = &lt;span class="Keyword"&gt;new&lt;/span&gt; Dictionary&amp;lt;T, &lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; List&amp;lt;Exception&amp;gt; exceptions = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Exception&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (&lt;span class="Keyword"&gt;true&lt;/span&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;span class="Modifier"&gt;await&lt;/span&gt; TaskEx.WhenAny(tasks);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; newTasks = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; task &lt;span class="Statement"&gt;in&lt;/span&gt; tasks)    &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;span class="Statement"&gt;switch&lt;/span&gt; (task.Status)    &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; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Canceled:    &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; failures++;    &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; &lt;span class="Statement"&gt;break&lt;/span&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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Faulted:    &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; failures++;    &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; exceptions.Add(task.Exception.Flatten());    &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; &lt;span class="Statement"&gt;break&lt;/span&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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.RanToCompletion:    &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; &lt;span class="ValueType"&gt;int&lt;/span&gt; count;    &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; &lt;span class="InlineComment"&gt;// Doesn&amp;#39;t matter whether it was there before or not - we want 0 if not anyway&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; results.TryGetValue(task.Result, &lt;span class="MethodParameter"&gt;out&lt;/span&gt; count);    &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; count++;    &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (count &amp;gt; bestCount)    &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; {    &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; bestCount = count;    &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (count &amp;gt;= majority)    &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;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; task.Result;    &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;&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; }    &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; results[task.Result] = count;    &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; &lt;span class="Statement"&gt;break&lt;/span&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;span class="Modifier"&gt;default&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Keep going next time. may not be appropriate for Created&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; newTasks.Add(task);    &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; &lt;span class="Statement"&gt;break&lt;/span&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;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;span class="InlineComment"&gt;// The new list of tasks to wait for&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; tasks = newTasks;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// If we can&amp;#39;t possibly work, bail out.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (tasks.Count + bestCount &amp;lt; majority)    &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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AggregateException(&lt;span class="String"&gt;&amp;quot;No majority result possible&amp;quot;&lt;/span&gt;, exceptions);    &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;/div&gt;  &lt;p&gt;I should warn you that this &lt;em&gt;isn&amp;#39;t&lt;/em&gt; a particularly efficient implementation - it was just one I wrote until it worked. The basic steps are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Work out how many results make a majority, so we know when to stop&lt;/li&gt;    &lt;li&gt;Keep track of how many &amp;quot;votes&amp;quot; our most commonly-returned result has, along with the counts of &lt;em&gt;all&lt;/em&gt; the votes&lt;/li&gt;    &lt;li&gt;Repeatedly:&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;Wait (asynchronously) for &lt;em&gt;at least&lt;/em&gt; of the remaining tasks to finish (many may finish &amp;quot;at the same time&amp;quot;)&lt;/li&gt;      &lt;li&gt;Start a new list of &amp;quot;tasks we&amp;#39;re going to wait for next time&amp;quot;&lt;/li&gt;      &lt;li&gt;Process each task in the current list, taking an action on each state:&lt;/li&gt;      &lt;ul&gt;       &lt;li&gt;If it&amp;#39;s been cancelled, we&amp;#39;ll treat that as a failure (we could potentially treat &amp;quot;the majority have been cancelled&amp;quot; as a cancellation, but for the moment a failure is good enough)&lt;/li&gt;        &lt;li&gt;If it&amp;#39;s faulted, we&amp;#39;ll add the exception to the list of exceptions, so that if the overall result ends up as failure, we can throw an AggregateException with all of the individual exceptions&lt;/li&gt;        &lt;li&gt;If it&amp;#39;s finished successfully, we&amp;#39;ll check the result:&lt;/li&gt;        &lt;ul&gt;         &lt;li&gt;Add 1 to the count for that result (the dictionary will use the default comparer for the result type, which we assume is good enough)&lt;/li&gt;          &lt;li&gt;If this is greater than the previous &amp;quot;winner&amp;quot; (which could be for the same result), check for it being actually an overall majority, and return if so.&lt;/li&gt;       &lt;/ul&gt;        &lt;li&gt;If it&amp;#39;s still running (or starting), add it to the new task list&lt;/li&gt;     &lt;/ul&gt;      &lt;li&gt;Check whether enough tasks have failed - or given different results - so ensure that a majority is now impossible. If so, throw an AggregateException to say so. This &lt;em&gt;may&lt;/em&gt; have some exceptions, but it may not (if there are three tasks which gave different results, none of them actually &lt;em&gt;failed&lt;/em&gt;)&lt;/li&gt;   &lt;/ul&gt; &lt;/ul&gt;  &lt;p&gt;Each iteration of the &amp;quot;repeatedly&amp;quot; will have a smaller list to check than before, so we&amp;#39;ll definitely terminate at some point.&lt;/p&gt;  &lt;p&gt;I mentioned that it&amp;#39;s inefficient. In particular, we&amp;#39;re ignoring the fact that WhenAny returns a Task&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt;, so awaiting that will actually tell us &lt;em&gt;a&lt;/em&gt; task which has finished. We don&amp;#39;t need to loop over the whole collection at that point - we could just remove that single task from the collection. We could do that efficiently if we kept a Dictionary&amp;lt;Task&amp;lt;T&amp;gt;, LinkedListNode&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; and a LinkedList&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; - we&amp;#39;d just look up the task which had completed in the dictionary, remove its node from the list, and remove the entry from the dictionary. We wouldn&amp;#39;t need to create a new collection each time, or iterate through all of the old one. However, that&amp;#39;s a job for another day... as is allowing a cancellation token to be passed in, and a custom equality comparer.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;So we can make this implementation smarter and more flexible, certainly - but it&amp;#39;s not insanely tricky to write. I&amp;#39;m &lt;em&gt;reasonably&lt;/em&gt; confident that it works, too - as I have unit tests for it. They&amp;#39;ll come in the next part. The important point&amp;#160; from this post is that by sticking within the Task&amp;lt;T&amp;gt; world, we can &lt;em&gt;reasonably easily&lt;/em&gt; create building blocks to allow for composition of asynchronous operations. While it would be nice to have someone more competent than myself write a bullet-proof, efficient implementation of this operation, I wouldn&amp;#39;t feel too unhappy using a homegrown one in production. The same could &lt;em&gt;not&lt;/em&gt; have been said pre-async/await. I just wouldn&amp;#39;t have had a chance of getting it right.&lt;/p&gt;  &lt;p&gt;Next up - the unit tests for this code, in which I introduce the TimeMachine class.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1802817" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 14: Data passing in coroutines</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/29/eduasync-part-14-data-passing-in-coroutines.aspx</link><pubDate>Wed, 29 Jun 2011 17:18:20 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1795430</guid><dc:creator>skeet</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1795430</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1795430</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/29/eduasync-part-14-data-passing-in-coroutines.aspx#comments</comments><description>&lt;p&gt;(This post covers project 19 in the &lt;a href="http://code.google.com/p/eduasync/source/browse/"&gt;source code&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Last time we looked at independent coroutines running in a round-robin fashion. This time we&amp;#39;ll keep the round-robin scheduling, but add in the idea of passing data from one coroutine to another. Each coroutine will act on data of the same type, which is necessary for the scheme to work when one coroutine could &amp;quot;drop out&amp;quot; of the chain by returning.&lt;/p&gt;  &lt;h3&gt;Designing the data flow&lt;/h3&gt;  &lt;p&gt;It took me a while to get to the stage where I was happy with the design of how data flowed around these coroutines. I knew I wanted a coordinator as before, and that it should have a Yield method taking the value to pass to the next coroutine and returning an awaitable which would provide the next value when it completed. The tricky part was working out what to do at the start of each method and the end. If the method just took a Coordinator parameter, we wouldn&amp;#39;t have anything to do with the value yielded by the first coroutine, because the second coroutine wouldn&amp;#39;t be ready to accept it yet. Likewise when a coroutine completed, we wouldn&amp;#39;t have another value to pass to the next coroutine.&lt;/p&gt;  &lt;p&gt;Writing these dilemmas out in this post, the solution seems blindingly obvious of course: each coroutine should accept a data value on entry, and return one at the end. At any point where we transfer control, we &lt;em&gt;provide&lt;/em&gt; a value and have a value which is &lt;em&gt;required&lt;/em&gt; by something. The final twist is to make the coordinator&amp;#39;s Start method take an initial value and return the value returned by the last coroutine to complete.&lt;/p&gt;  &lt;p&gt;So, that&amp;#39;s the theory... let&amp;#39;s look at the implementation.&lt;/p&gt;  &lt;h3&gt;Initialization&lt;/h3&gt;  &lt;p&gt;I&amp;#39;ve changed the coordinator to take all the coroutines as a constructor parameter (of the somewhat fearsome declaration &amp;quot;params Func&amp;lt;Coordinator&amp;lt;T&amp;gt;, T, Task&amp;lt;T&amp;gt;&amp;gt;[] coroutines&amp;quot;) which means we don&amp;#39;t need to implement IEnumerable pointlessly any more.&lt;/p&gt;  &lt;p&gt;This leads to a code skeleton of this form:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; coordinator = &lt;span class="Keyword"&gt;new&lt;/span&gt; Coordinator&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;(FirstCoroutine,     &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;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; SecondCoroutine,     &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;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThirdCoroutine);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; finalResult = coordinator.Start(&lt;span class="String"&gt;&amp;quot;m1&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Final result: {0}&amp;quot;&lt;/span&gt;, finalResult);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; FirstCoroutine(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Coordinator&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; coordinator,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; initialValue)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ...     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Same signature for SecondCoroutine and ThirdCoroutine&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Last time we simply had a Queue&amp;lt;Action&amp;gt; internally in the coordinator as the actions to invoke. You might be &lt;em&gt;expecting&lt;/em&gt; a Queue&amp;lt;Func&amp;lt;T, T&amp;gt;&amp;gt; this time - after all, we&amp;#39;re passing in data and returning data at each point. However, the mechanism for that data transfer is &amp;quot;out of band&amp;quot; so to speak. The only time we really &amp;quot;return&amp;quot; an item is when we reach the end of a coroutine. Usually we&amp;#39;ll be providing data to the next step using a method. Likewise the only time a coroutine is &lt;em&gt;given&lt;/em&gt; data directly is in the first call - after that, it will have to &lt;em&gt;fetch&lt;/em&gt; the value by calling GetResult() on the awaiter which it uses to yield control.&lt;/p&gt;  &lt;p&gt;All of this is leading to a requirement for our constructor to convert each coroutine delegate into a simple Action. The trick is working out how to deal with the data flow. I&amp;#39;m going to include SupplyValue() and ConsumeValue() methods within the coordinator for the awaiter to use, so it&amp;#39;s just a case of calling those appropriately from our action. In particular:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;When the action is called, it should consume the current value. &lt;/li&gt;    &lt;li&gt;It should then call the coroutine passing in the coordinator (&amp;quot;this&amp;quot;) and the initial value. &lt;/li&gt;    &lt;li&gt;When the task returned by the coroutine has completed, the result of that task should be used to supply a new value. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The only tricky part here is the last bullet - and it&amp;#39;s not that hard really, so long as we remember that we&amp;#39;re absolutely &lt;em&gt;not&lt;/em&gt; trying to start any new threads. We just want to hook onto the end of the task, getting a chance to supply the value before the next coroutine tries to pick it up. We can do that using Task.ContinueWith, but passing in TaskContinuationOptions.ExecuteSynchronously so that we use the same thread that the task completes on to execute the continuation.&lt;/p&gt;  &lt;p&gt;At this point we can implement the initialization part of the coordinator, assuming the presence of SupplyValue() and ConsumeValue():&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Coordinator&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Queue&amp;lt;Action&amp;gt; actions;     &lt;br /&gt;&lt;span class="Modifier"&gt;&amp;#160;&amp;#160;&amp;#160; private&lt;/span&gt; &lt;span class="Modifier"&gt;readonly&lt;/span&gt; Awaitable awaitable;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Coordinator(&lt;span class="MethodParameter"&gt;params&lt;/span&gt; Func&amp;lt;Coordinator&amp;lt;T&amp;gt;, T, Task&amp;lt;T&amp;gt;&amp;gt;[] coroutines)     &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;span class="InlineComment"&gt;// We can&amp;#39;t refer to &amp;quot;this&amp;quot; in the variable initializer. We can use&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// the same awaitable for all yield calls.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.awaitable = &lt;span class="Keyword"&gt;new&lt;/span&gt; Awaitable(&lt;span class="Keyword"&gt;this&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; actions = &lt;span class="Keyword"&gt;new&lt;/span&gt; Queue&amp;lt;Action&amp;gt;(coroutines.Select(ConvertCoroutine));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Converts a coroutine into an action which consumes the current value,&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// calls the coroutine, and attaches a continuation to it so that the return&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// value is used as the new value.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt; Action ConvertCoroutine(Func&amp;lt;Coordinator&amp;lt;T&amp;gt;, T, Task&amp;lt;T&amp;gt;&amp;gt; coroutine)     &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;span class="Statement"&gt;return&lt;/span&gt; () =&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; Task&amp;lt;T&amp;gt; task = coroutine(&lt;span class="Keyword"&gt;this&lt;/span&gt;, ConsumeValue());     &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; task.ContinueWith(ignored =&amp;gt; SupplyValue(task.Result),     &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; 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; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;I&amp;#39;ve broken ConvertCoroutine into a separate method so that we can use it as the projection for the Select call within the constructor. I did &lt;em&gt;initially&lt;/em&gt; have it within a lambda expression within the constructor, but it was utterly hideous in terms of readabililty.&lt;/p&gt;  &lt;p&gt;One suggestion I&amp;#39;ve received is that I could declare a new delegate type instead of using Func&amp;lt;Coordinator&amp;lt;T&amp;gt;, T, Task&amp;lt;T&amp;gt;&amp;gt; to represent a coroutine. This could either be a non-generic delegate nested in the generic coordinator class, or a generic stand-alone delegate:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;delegate&lt;/span&gt; T Coroutine&amp;lt;T&amp;gt;(Coordinator&amp;lt;T&amp;gt; coordinator, T initialValue);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Or nested...&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Coordinator&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;delegate&lt;/span&gt; T Coroutine(Coordinator&amp;lt;T&amp;gt; coordinator, T initialValue);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Both of these would work perfectly well. I haven&amp;#39;t made the change at the moment, but it&amp;#39;s certainly worth considering. The debate about whether to use custom delegate types or Func/Action is one for another blog post, I think :)&lt;/p&gt;  &lt;p&gt;The one bit of the initialization I haven&amp;#39;t explained yet is the &amp;quot;awaitable&amp;quot; field and the Awaitable type. They&amp;#39;re to do with yielding - so let&amp;#39;s look at them now.&lt;/p&gt;  &lt;h3&gt;Yielding and transferring data&lt;/h3&gt;  &lt;p&gt;Next we need to work out how we&amp;#39;re going to transfer data and control between the coroutines. As I&amp;#39;ve mentioned, we&amp;#39;re going to use a method within the coordinator, called from the coroutines, to accomplish this. The coroutines have this sort of code:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; FirstCoroutine(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Coordinator&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; coordinator,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; initialValue)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Starting FirstCoroutine with initial value {0}&amp;quot;&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; initialValue);&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; ...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; received = &lt;span class="Modifier"&gt;await&lt;/span&gt; coordinator.Yield(&lt;span class="String"&gt;&amp;quot;x1&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Returned to FirstCoroutine with value {0}&amp;quot;&lt;/span&gt;, received);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="String"&gt;&amp;quot;x3&amp;quot;&lt;/span&gt;;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The method name &amp;quot;Yield&amp;quot; here is a double-edged sword. The word has two meanings - yielding a value to be used elsewhere, and yielding control until we&amp;#39;re called back. Normally it&amp;#39;s not ideal to use a name that can mean subtly different things - but in this case we actually &lt;em&gt;want&lt;/em&gt; both of these meanings.&lt;/p&gt;  &lt;p&gt;So, what does Yield need to do? Well, the flow control should look something like this:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Coroutine calls Yield() &lt;/li&gt;    &lt;li&gt;Yield() calls SupplyValue() internally to remember the new value to be consumed by the next coroutine &lt;/li&gt;    &lt;li&gt;Yield() returns an awaitable to the coroutine &lt;/li&gt;    &lt;li&gt;Due to the await expression, the coroutine calls GetAwaiter() on the awaitable to get an awaiter &lt;/li&gt;    &lt;li&gt;The coroutine checks IsCompleted on the awaiter, which must return false (to prompt the remaining behaviour) &lt;/li&gt;    &lt;li&gt;The coroutine calls OnCompleted() passing in the continuation for the rest of the method &lt;/li&gt;    &lt;li&gt;The coroutine returns to its caller &lt;/li&gt;    &lt;li&gt;The coordinator proceeds with the next coroutine &lt;/li&gt;    &lt;li&gt;When we eventually get back to this coroutine, it will call GetResult() to get the &amp;quot;current value&amp;quot; to assign to the &amp;quot;received&amp;quot; variable. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now you&amp;#39;ll see that Yield() needs to return some kind of awaitable type - in other words, one with a GetAwaiter() method. Previously we put this directly on the Coordinator type, and we &lt;em&gt;could&lt;/em&gt; have done that here - but I don&amp;#39;t really want anyone to just &amp;quot;await coordinator&amp;quot; accidentally. You should really need to call Yield() in order to get an awaitable. So we have an Awaitable type, nested in Coordinator.&lt;/p&gt;  &lt;p&gt;We then need to decide what the &lt;em&gt;awaiter&lt;/em&gt; type is - the result of calling GetAwaiter() on the awaitable. This time I decided to use the Coordinator itself. That means people &lt;em&gt;could&lt;/em&gt; accidentally call IsCompleted, OnCompleted() or GetResult(), but I figured that wasn&amp;#39;t too bad. If we were to go to the extreme, we&amp;#39;d create another type just for the Awaiter as well. It would need to have a reference to the coordinator of course, in order to actually do its job. As it is, we can make the Awaitable just return the Coordinator that created it. (Awaitable is nested within Coordinator&amp;lt;T&amp;gt;, which is how it can refer to T without being generic itself.)&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Awaitable     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Coordinator&amp;lt;T&amp;gt; coordinator;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt; Awaitable(Coordinator&amp;lt;T&amp;gt; coordinator)     &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;span class="Keyword"&gt;this&lt;/span&gt;.coordinator = coordinator;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Coordinator&amp;lt;T&amp;gt; GetAwaiter()     &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;span class="Statement"&gt;return&lt;/span&gt; coordinator;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The only state here is the coordinator, which is why we create an instance of Awaitable on the construction of the Coordinator, and keep it around.&lt;/p&gt;  &lt;p&gt;Now Yield() is really simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; Awaitable Yield(T value)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; SupplyValue(value);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; awaitable;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So to recap, we now just need the awaiter members, SupplyValue() and ConsumeValue(). Let&amp;#39;s look at the awaiter members (in Coordinator) to start with. We already know that IsCompleted will just return false. OnCompleted() just needs to stash the continuation in the queue, and GetResult() just needs to consume the &amp;quot;current&amp;quot; value and return it:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;false&lt;/span&gt;; } }     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action continuation)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; actions.Enqueue(continuation);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; T GetResult()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; ConsumeValue();     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Simple, huh? Finally, consuming and supplying values:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt; T currentValue;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; valuePresent;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SupplyValue(T value)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (valuePresent)     &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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; InvalidOperationException     &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;span class="String"&gt;&amp;quot;Attempt to supply value when one is already present&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; currentValue = value;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; valuePresent = &lt;span class="Keyword"&gt;true&lt;/span&gt;;     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt; T ConsumeValue()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (!valuePresent)     &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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; InvalidOperationException     &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;span class="String"&gt;&amp;quot;Attempt to consume value when it isn&amp;#39;t present&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; T oldValue = currentValue;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; valuePresent = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; currentValue = &lt;span class="Modifier"&gt;default&lt;/span&gt;(T);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; oldValue;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;These are relatively long methods (compared with the other ones I&amp;#39;ve shown) but pretty simple. Hopefully they don&amp;#39;t need explanation :)&lt;/p&gt;  &lt;h3&gt;The results&lt;/h3&gt;  &lt;p&gt;Now that everything&amp;#39;s in place, we can run it. I haven&amp;#39;t posted the full code of the coroutines, but you can &lt;a href="http://code.google.com/p/eduasync/source/browse/src/HomogeneousCoroutines/Program.cs"&gt;see it on Google Code&lt;/a&gt;. Hopefully the results speak for themselves though - you can see the relevant values passing from one coroutine to another (and in and out of the Start method).&lt;/p&gt;  &lt;div class="code"&gt;Starting FirstCoroutine with initial value m1   &lt;br /&gt;Yielding &amp;#39;x1&amp;#39; from FirstCoroutine...    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Starting SecondCoroutine with initial value x1    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Starting SecondCoroutine    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding &amp;#39;y1&amp;#39; from SecondCoroutine...    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Starting ThirdCoroutine with initial value y1    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Yielding &amp;#39;z1&amp;#39; from ThirdCoroutine...    &lt;br /&gt;Returned to FirstCoroutine with value z1    &lt;br /&gt;Yielding &amp;#39;x2&amp;#39; from FirstCoroutine...    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine with value x2    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding &amp;#39;y2&amp;#39; from SecondCoroutine...    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Returned to ThirdCoroutine with value y2    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Finished ThirdCoroutine...    &lt;br /&gt;Returned to FirstCoroutine with value z2    &lt;br /&gt;Finished FirstCoroutine    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine with value x3    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding &amp;#39;y3&amp;#39; from SecondCoroutine...    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine with value y3    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Finished SecondCoroutine    &lt;br /&gt;Final result: y4 &lt;/div&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;I&amp;#39;m not going to claim this is the world&amp;#39;s most useful coroutine model - or indeed useful at all. As ever, I&amp;#39;m more interested in thinking about how data and control flow can be modelled than actual usefulness.&lt;/p&gt;  &lt;p&gt;In this case, it was the realization that &lt;em&gt;everything&lt;/em&gt; should accept and return a value of the same type which really made it all work. After that, the actual code is pretty straightforward. (At least, I think it is - please let me know if any bits are confusing, and I&amp;#39;ll try to elaborate on them.)&lt;/p&gt;  &lt;p&gt;Next time we&amp;#39;ll look at something more like a pipeline model - something remarkably reminiscent of LINQ, but without taking up as much stack space (and with vastly worse readability, of course). Unfortunately the current code reaches the limits of my ability to understand why it works, which means it far exceeds my ability to &lt;em&gt;explain&lt;/em&gt; why it works. Hopefully I can simplify it a bit over the next few days.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1795430" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 13: first look at coroutines with async</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-13-first-look-at-coroutines-with-async.aspx</link><pubDate>Wed, 22 Jun 2011 20:37:30 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1795089</guid><dc:creator>skeet</dc:creator><slash:comments>14</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1795089</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1795089</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-13-first-look-at-coroutines-with-async.aspx#comments</comments><description>&lt;p&gt;(This part covers project 18 in the &lt;a href="http://code.google.com/p/eduasync/source/browse/"&gt;source code&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;As I mentioned in earlier parts, the &amp;quot;awaiting&amp;quot; part of async methods is in no way limited to tasks. So long as we have a suitable GetAwaiter() method which returns a value of a type which in turn has suitable methods on it, the compiler doesn&amp;#39;t really care what&amp;#39;s going on. It&amp;#39;s time to exploit that to implement some form of &lt;a href="http://en.wikipedia.org/wiki/Coroutine"&gt;coroutines&lt;/a&gt; in C#.&lt;/p&gt;  &lt;h3&gt;Introduction to coroutines&lt;/h3&gt;  &lt;p&gt;The fundamental idea of coroutines is to have multiple methods executing cooperatively, each of them maintaining their position within the coroutine when they yield to another. You can &lt;em&gt;almost&lt;/em&gt; think of them as executing in multiple threads, with only one thread actually &lt;em&gt;running&lt;/em&gt; at a time, and signalling between the different threads to control flow. However, we don&amp;#39;t really need multiple threads once we&amp;#39;ve got continuations - we can have a single thread with a complex flow of continuations, and still only a very short &amp;quot;real&amp;quot; stack. (The control flow is stored in normal collections instead of being implicit on the thread&amp;#39;s stack.)&lt;/p&gt;  &lt;p&gt;Coroutines were already feasible in C# through the use of iterator blocks, but the async feature of C# allows a slightly more natural way of expressing them, in my view. (The linked Wikipedia page gives a sketch of how coroutines can be built on top of &lt;em&gt;generators&lt;/em&gt;, which in the general concept that iterator blocks implement in C#.)&lt;/p&gt;  &lt;p&gt;I have implemented various flavours of coroutines in Eduasync. It&amp;#39;s possible that some (all?) of them shouldn&amp;#39;t &lt;em&gt;strictly &lt;/em&gt;be called coroutines, but they&amp;#39;re close enough to the real thing in feeling. This is far from an exhaustive set of approaches. Once you&amp;#39;ve got the basic idea of what I&amp;#39;m doing, you may well want to experiment with your own implementations.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;not&lt;/em&gt; going to claim that the use of coroutines in any of my examples really makes any sense in terms of making real tasks easier. This is &lt;em&gt;purely&lt;/em&gt; for the sake of interest and twisting the async feature for fun.&lt;/p&gt;  &lt;h3&gt;Round-robin independent coroutines&lt;/h3&gt;  &lt;p&gt;Our first implementation of coroutines is relatively simple. A &lt;em&gt;coordinator&lt;/em&gt; effectively &amp;quot;schedules&amp;quot; the coroutines it&amp;#39;s set up with in a round-robin fashion: when one of the coroutines yields control to the coordinator, the coordinator remembers where the coroutine had got to, and then starts the next one. When each coroutine has executed its first piece of code and yielded control, the coordinator will go back to the first coroutine to continue execution, and so on until all coroutines have completed.&lt;/p&gt;  &lt;p&gt;The coroutines don&amp;#39;t know about each other, and no data is being passed between them.&lt;/p&gt;  &lt;p&gt;Hopefully it&amp;#39;s reasonably obvious that the coordinator contains all the smarts here - the coroutines themselves can be relatively dumb. Let&amp;#39;s look at what the client code looks like (along with the results) before we get to the coordinator code.&lt;/p&gt;  &lt;h3&gt;Client code&lt;/h3&gt;  &lt;p&gt;The sample code contains three coroutines, all of which take a Coordinator parameter and have a void return type. These are passed to a new coordinator using a collection initializer and method group conversions; the coordinator is then started. Here&amp;#39;s the entry point code for this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; coordinator = &lt;span class="Keyword"&gt;new&lt;/span&gt; Coordinator {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; FirstCoroutine,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; SecondCoroutine,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; coordinator.Start();     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;When each coroutine is initially started, the coordinator passes a reference to &lt;em&gt;itself&lt;/em&gt; as the argument to the coroutine. That&amp;#39;s how we solve the chicken-and-egg problem of the coroutine and coordinator having to know about each other. The way a coroutine yields control is simply by awaiting the coordinator. The result type of this await expression is void - it&amp;#39;s just a way of &amp;quot;pausing&amp;quot; the coroutine.&lt;/p&gt;  &lt;p&gt;We&amp;#39;re not doing anything interesting in the actual coroutines - just tracing the execution flow. Of course we &lt;em&gt;could&lt;/em&gt; do anything we wanted, within reason. We could even await a &lt;em&gt;genuinely&lt;/em&gt; asynchronous task such as fetching a web page asynchronously. In that case the whole coroutine collection would be &amp;quot;paused&amp;quot; until the fetch returned.&lt;/p&gt;  &lt;p&gt;Here&amp;#39;s the code for the first coroutine - the second and third ones are similar, but use different indentation for clarity. The third coroutine is also shorter, just for fun - it only awaits the coordinator once.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; FirstCoroutine(Coordinator coordinator)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Starting FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Yielding from FirstCoroutine...&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; coordinator;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Returned to FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Yielding from FirstCoroutine again...&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; coordinator;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Returned to FirstCoroutine again&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Finished FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And here&amp;#39;s the output...&lt;/p&gt;  &lt;div class="code"&gt;Starting FirstCoroutine    &lt;br /&gt;Yielding from FirstCoroutine...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Starting SecondCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding from SecondCoroutine...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Starting ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Yielding from ThirdCoroutine...     &lt;br /&gt;Returned to FirstCoroutine     &lt;br /&gt;Yielding from FirstCoroutine again...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding from SecondCoroutine again...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Returned to ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Finished ThirdCoroutine...     &lt;br /&gt;Returned to FirstCoroutine again     &lt;br /&gt;Finished FirstCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine again     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Finished SecondCoroutine &lt;/div&gt;  &lt;p&gt;Hopefully that&amp;#39;s the output you expected, given the earlier description. Again it may help if you think of the coroutines as running in separate pseudo-threads: the execution within each pseudo-thread is just linear, and the timing is controlled by our explicit &amp;quot;await&amp;quot; expressions. All of this would actually be pretty easy to implement using multiple threads which really &lt;em&gt;did&lt;/em&gt; just block on each await expression - but the fun part is keeping it all in one real thread. Let&amp;#39;s have a look at the coordinator.&lt;/p&gt;  &lt;h3&gt;The Coordinator class&lt;/h3&gt;  &lt;p&gt;Some of the later coroutine examples end up being slightly brainbusting, at least for me. This one is relatively straightforward though, once you&amp;#39;ve got the basic idea. All we need is a &lt;em&gt;queue&lt;/em&gt; of actions to execute. After initialization, we want our queue to contain the coroutine starting points.&lt;/p&gt;  &lt;p&gt;When a coroutine yields control, we just need to add the remainder of it to the end of the queue, and move on to the next item. Obviously the async infrastructure will provide &amp;quot;the remainder of the coroutine&amp;quot; as a continuation via the OnContinue method.&lt;/p&gt;  &lt;p&gt;When a coroutine just returns, we continue with the next item in the queue as before - it&amp;#39;s just that we won&amp;#39;t add a continuation to the end of the queue. Eventually (well, hopefully) we&amp;#39;ll end up with an empty queue, at which point we can stop.&lt;/p&gt;  &lt;h3&gt;Initialization and a choice of data structures&lt;/h3&gt;  &lt;p&gt;We&amp;#39;ll represent our queue using Queue&amp;lt;T&amp;gt; where the T is a delegate type. We have two choices here though, because we have two kinds of delegate - one which takes the Coordinator as a parameter (for the initial coroutine setup) and one which has no parameters (for the continuations). Fortunately we can convert between the two in either direction very simply, bearing in mind that all of this is within the context of a coordinator. For example:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// If we&amp;#39;re given a coroutine and want a plain Action &lt;/span&gt;    &lt;br /&gt;Action&amp;lt;Coordinator&amp;gt; coroutine = ...;&amp;#160; &lt;br /&gt;Action action = () =&amp;gt; coroutine(&lt;span class="Keyword"&gt;this&lt;/span&gt;);    &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// If we&amp;#39;re given a plain Action and want an Action&amp;lt;Continuation&amp;gt;: &lt;/span&gt;    &lt;br /&gt;Action continuation = ...;&amp;#160; &lt;br /&gt;Action&amp;lt;Coordinator&amp;gt; coroutine = ignored =&amp;gt; continuation(); &lt;/div&gt;  &lt;p&gt;I&amp;#39;ve arbitrarily chosen to use the first option, so there&amp;#39;s a Queue&amp;lt;Action&amp;gt; internally.&lt;/p&gt;  &lt;p&gt;Now we need to get the collection initializer working. The C# compiler requires an appropriate Add method (which is easy) and also checks that the type implements IEnumerable. We don&amp;#39;t really need to be able to iterate over the queue of actions, so I&amp;#39;ve use explicit interface implementation to reduce the likelihood of GetEnumerator() being called inappropriately, and made the method throw an exception for good measure. That gives us the skeleton of the class required for setting up:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Coordinator : IEnumerable    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Queue&amp;lt;Action&amp;gt; actions = &lt;span class="Keyword"&gt;new&lt;/span&gt; Queue&amp;lt;Action&amp;gt;();    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Used by collection initializer to specify the coroutines to run&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Add(Action&amp;lt;Coordinator&amp;gt; coroutine)    &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; actions.Enqueue(() =&amp;gt; coroutine(&lt;span class="Keyword"&gt;this&lt;/span&gt;));    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Required for collection initializers, but we don&amp;#39;t really want&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// to expose anything.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; IEnumerator IEnumerable.GetEnumerator()    &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;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; NotSupportedException(&lt;span class="String"&gt;&amp;quot;IEnumerable only supported to enable collection initializers&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(Note that I haven&amp;#39;t used XML documentation anywhere here - it&amp;#39;s great for real code, but adds clutter in blog posts.)&lt;/p&gt;  &lt;p&gt;For production code I&amp;#39;d probably prevent Add from being called after the coordinator had been started, but there&amp;#39;s no need to do it in our well-behaved sample code. We&amp;#39;re only going to add extra actions to the queue via continuations, which will be added due to await expressions.&lt;/p&gt;  &lt;h3&gt;The main execution loop and async infrastructure&lt;/h3&gt;  &lt;p&gt;So far we&amp;#39;ve got code to register coroutines in the queue - so now we need to execute them. Bearing in mind that the actions themselves will be responsible for adding continuations, the main loop of the coordinator is embarrassingly simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Execute actions in the queue until it&amp;#39;s empty. Actions add *more*&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// actions (continuations) to the queue by awaiting this coordinator.&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Start()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (actions.Count &amp;gt; 0)    &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; actions.Dequeue().Invoke();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Of course, the interesting bit is the code which supports the async methods and await expressions. We know we need to provide a GetAwaiter() method, but what should that return? Well, we&amp;#39;re just going to use the awaiter to add a continuation to the coordinator&amp;#39;s queue. It&amp;#39;s got no other state than that - so we might as well return the coordinator itself, and put the other infrastructure methods directly in the coordinator.&lt;/p&gt;  &lt;p&gt;Again, this is &lt;em&gt;slightly&lt;/em&gt; ugly, as the extra methods don&amp;#39;t really make sense on the coordinator - we wouldn&amp;#39;t want to call them directly from client code, for example. However, they&amp;#39;re fairly irrelevant - we could always create a nested type which just had a reference to its &amp;quot;parent&amp;quot; coordinator if we wanted to. For simplicity, I haven&amp;#39;t bothered with this - I&amp;#39;ve just implemented GetAwaiter() trivially:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Used by await expressions to get an awaiter&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; Coordinator GetAwaiter()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;this&lt;/span&gt;;    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So, that leaves just three members still to implement: IsCompleted, OnCompleted and GetResult. We always want the IsCompleted property to return false, as otherwise the coroutine will just continue executing &lt;em&gt;immediately&lt;/em&gt; without returning to cede control; the await expression would be pointless. OnCompleted &lt;em&gt;just&lt;/em&gt; needs to add the continuation to the end of the queue - we don&amp;#39;t need to attach it to a task, or anything like that. Finally, GetResult is a no-op - we have no results, no exceptions, and basically nothing to do. You might want to add a bit of logging here, if you were so inclined, but there&amp;#39;s no real need.&lt;/p&gt;  &lt;p&gt;So, here are the final three members of Coordinator:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Force await to yield control&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;false&lt;/span&gt;; } }    &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action continuation)    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Put the continuation at the end of the queue, ready to&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// execute when the other coroutines have had a go.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; actions.Enqueue(continuation);    &lt;br /&gt;}    &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; GetResult()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Our await expressions are void, and we never need to throw&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// an exception, so this is a no-op.&lt;/span&gt;    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And that&amp;#39;s it! Fewer than 50 lines of code required, and nothing complicated at all. The interesting behaviour is all due to the way the C# compiler &lt;em&gt;uses&lt;/em&gt; the coordinator when awaiting it.&lt;/p&gt;  &lt;p&gt;We need AsyncVoidMethodBuilder as before, as we have some async void methods - but that doesn&amp;#39;t need to do anything significant. That&amp;#39;s basically all the code required to implement these basic round-robin coroutines.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Our first foray into the weird and wonderful world of coroutines was relatively tame. The basic idea of a coordinator keeping track of the state of all the different coroutines in one sense or another will keep coming back to us, but with different ways of controlling the execution flow.&lt;/p&gt;  &lt;p&gt;Next time we&amp;#39;ll see some coroutines which can pass data to each other.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1795089" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 12: Observing all exceptions</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-12-observing-all-exceptions.aspx</link><pubDate>Wed, 22 Jun 2011 06:04:20 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1795042</guid><dc:creator>skeet</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1795042</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1795042</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-12-observing-all-exceptions.aspx#comments</comments><description>&lt;p&gt;(This post covers projects 16 and 17 in the &lt;a href="http://eduasync.googlecode.com/"&gt;source code&lt;/a&gt;.) &lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling.aspx"&gt;Last time&lt;/a&gt; we looked at unwrapping an AggregateException when we await a result. While there are potentially other interesting things we could look at with respect to exceptions (particularly around cancellation) I&amp;#39;m just going to touch on &lt;em&gt;one&lt;/em&gt; extra twist that the async CTP implements before I move on to some weird ways of using async.&lt;/p&gt;  &lt;h3&gt;TPL and unobserved exceptions&lt;/h3&gt;  &lt;p&gt;The Task Parallel Library (TPL) on which the async support is based has some interesting behaviour around exceptions. Just as it’s entirely possible for more than one thing to go wrong with a particular task, it&amp;#39;s &lt;em&gt;also&lt;/em&gt; quite easy to miss some errors, if you&amp;#39;re not careful.&lt;/p&gt;  &lt;p&gt;Here&amp;#39;s a simple example of an async method in C# 5 where we create two tasks, both of which will throw exceptions:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; CauseTwoFailures()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; firstTask = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; InvalidOperationException();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; secondTask = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; InvalidOperationException();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; });     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; firstValue = &lt;span class="Modifier"&gt;await&lt;/span&gt; firstTask;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; secondValue = &lt;span class="Modifier"&gt;await&lt;/span&gt; secondTask;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; firstValue + secondValue;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now the timing of the two tasks is actually irrelevant here. The first task will &lt;em&gt;always&lt;/em&gt; throw an exception, which means we&amp;#39;re never going to &lt;em&gt;await&lt;/em&gt; the second task. That means there&amp;#39;s never any code which asks for the second task&amp;#39;s result, or adds a continuation to it. It&amp;#39;s alone and unloved in a cruel world, with no-one to observe the exception it throws.&lt;/p&gt;  &lt;p&gt;If we call this method from the Eduasync code we&amp;#39;ve got at the moment, and wait for long enough (I&amp;#39;ve got a call to &lt;a href="http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx"&gt;GC.WaitForPendingFinalizers&lt;/a&gt; in the same code) the program will abort, with this error:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Unhandled Exception: System.AggregateException: A Task&amp;#39;s exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---&amp;gt; System.InvalidOperationException: Operation is not valid due to the current state of the object.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Ouch. The TPL takes a hard line on unobserved exceptions. They indicate failures (presumably) which you&amp;#39;ll never find out about until you start caring about the result of a task. Basically there are various ways of &amp;quot;observing&amp;quot; a task&amp;#39;s failure, whether by performing some act which causes it to be thrown (usually as part of an AggregateException) or just asking for the exception for a task which is known to be faulted. An unobserved exception will throw an InvalidOperationException in its finalizer, usually causing the process to exit.&lt;/p&gt;  &lt;p&gt;That works well in &amp;quot;normal&amp;quot; TPL code, where you&amp;#39;re explicitly managing tasks - but it&amp;#39;s not so handy in async, where perfectly reasonable looking code which starts a few tasks and then awaits them one at a time (possibly doing some processing in between) might hide an unobserved exception.&lt;/p&gt;  &lt;h3&gt;Observing all exceptions&lt;/h3&gt;  &lt;p&gt;Fortunately TPL provides a way of us to get out of the normal task behaviour. There&amp;#39;s an event &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception.aspx"&gt;TaskScheduler.UnobservedTaskException&lt;/a&gt; which is fired by the finalizer before it goes bang. The handlers of the event are allowed to observe the exception using &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.unobservedtaskexceptioneventargs.setobserved.aspx"&gt;UnobservedTaskExceptionEventArgs.SetObserved&lt;/a&gt; and can also check whether it&amp;#39;s &lt;em&gt;already&lt;/em&gt; been observed.&lt;/p&gt;  &lt;p&gt;So all we have to do is add a handler for the event and our program doesn&amp;#39;t crash any more:&lt;/p&gt;  &lt;div class="code"&gt;TaskScheduler.UnobservedTaskException += (sender, e) =&amp;gt;    &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Saving the day! This exception would have been unobserved: {0}&amp;quot;&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; e.Exception);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; e.SetObserved();     &lt;br /&gt;};&lt;/div&gt;  &lt;p&gt;In Eduasync this is currently &lt;em&gt;only&lt;/em&gt; performed explicitly, in project 17. In the async CTP something like this is performed as part of the type initializer for AsyncTaskMethodBuilder&amp;lt;T&amp;gt;, which you can unfortunately tell because that type initializer &lt;a href="http://stackoverflow.com/questions/6353807"&gt;crashes when running under medium trust&lt;/a&gt;. (That issue will be fixed before the final release.)&lt;/p&gt;  &lt;h3&gt;Global changes&lt;/h3&gt;  &lt;p&gt;This approach has a very significant effect: it changes the &lt;em&gt;global&lt;/em&gt; behaviour of the system. If you have a system which uses the TPL and you &lt;em&gt;want&lt;/em&gt; the existing .NET 4 behaviour of the process terminating when you have unobserved exceptions, you basically can&amp;#39;t use async at all - and if you use any code which does, you&amp;#39;ll see the more permissive behaviour.&lt;/p&gt;  &lt;p&gt;You could &lt;em&gt;potentially&lt;/em&gt; add your own event handler which aborted the application forcibly, but that&amp;#39;s not terribly nice either. You should quite possibly add a handler to at least &lt;em&gt;log&lt;/em&gt; these exceptions, so you can find out what&amp;#39;s been going wrong that you haven&amp;#39;t noticed.&lt;/p&gt;  &lt;p&gt;Of course, this only affects &lt;em&gt;unobserved&lt;/em&gt; exceptions - anything you&amp;#39;re already observing will not be affected. Still, it&amp;#39;s a pretty big change. I wouldn&amp;#39;t be surprised if this aspect of the behaviour of async in C# 5 changed before release; it feels to me like it isn&amp;#39;t quite right yet. Admittedly I&amp;#39;m not sure &lt;em&gt;how&lt;/em&gt; I would suggest changing it, but effectively reversing the existing behaviour goes against Microsoft&amp;#39;s past behaviour when it comes to backwards compatibility. Watch this space.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;It&amp;#39;s worth pondering this whole issue yourself (and the one from last time), and making your feelings known to the team. I think it&amp;#39;s symptomatic of a wider problem in software engineering: we&amp;#39;re not really very good at handling errors. Java&amp;#39;s approach of checked exceptions didn&amp;#39;t turn out too well in my view, but the &amp;quot;anything goes&amp;quot; approach of C# has problems too... and introducing alternative models like the one in TPL makes things even more complicated. I don&amp;#39;t have any smart answers here - just that it&amp;#39;s something I&amp;#39;d like wiser people than myself to think about further.&lt;/p&gt;  &lt;p&gt;Next, we&amp;#39;re going to move a bit further away from the &amp;quot;normal&amp;quot; ways of using async, into the realm of &lt;a href="http://en.wikipedia.org/wiki/Coroutine"&gt;coroutines&lt;/a&gt;. This series is going to get increasingly obscure and silly, all in the name of really getting a feeling for the underlying execution model of async, before it possibly returns to more sensible topics such as task composition.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1795042" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 11: More sophisticated (but lossy) exception handling</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling.aspx</link><pubDate>Wed, 22 Jun 2011 05:25:46 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1795039</guid><dc:creator>skeet</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1795039</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1795039</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling.aspx#comments</comments><description>&lt;p&gt;(This post covers projects 13-15 in the &lt;a href="http://code.google.com/p/eduasync/source/browse/"&gt;source code&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Long-time readers of this blog may not learn much from this post - it&amp;#39;s mostly going over what I&amp;#39;ve &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2010/11/03/propagating-multiple-async-exceptions-or-not.aspx"&gt;covered before&lt;/a&gt;. Still, it&amp;#39;s new to Eduasync.&lt;/p&gt;  &lt;h3&gt;Why isn&amp;#39;t my exception being caught properly?&lt;/h3&gt;  &lt;p&gt;Exceptions are inherently problematic in C# 5. There are two conflicting aspects:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The point of the async feature in C# 5 is that you can write code which &lt;em&gt;mostly&lt;/em&gt; looks like its synchronous code. We expect to be able to catch specific exception types as normal. &lt;/li&gt;    &lt;li&gt;Asynchronous code may potentially have &lt;em&gt;multiple&lt;/em&gt; exceptions &amp;quot;at the same time&amp;quot;. The language simply isn&amp;#39;t designed to deal with that in the synchronous case. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now if the language had been designed for asynchrony to start with, perhaps exception flow would have been designed differently - but we are where we are, and we all expect exceptions to work in a certain way.&lt;/p&gt;  &lt;p&gt;Let&amp;#39;s make all of this concrete with a sample:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = FetchOrDefaultAsync();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Result: {0}&amp;quot;&lt;/span&gt;, task.Result);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; FetchOrDefaultAsync()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Nothing special about IOException here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;try&lt;/span&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; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; fetcher = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; { &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; IOException(); });     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;await&lt;/span&gt; fetcher;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;catch&lt;/span&gt; (IOException e)     &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(&lt;span class="String"&gt;&amp;quot;Caught IOException: {0}&amp;quot;&lt;/span&gt;, e);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 5;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;catch&lt;/span&gt; (Exception e)     &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(&lt;span class="String"&gt;&amp;quot;Caught arbitrary exception: {0}&amp;quot;&lt;/span&gt;, e);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 10;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Here we have a task which will throw an IOException, and some code which awaits that task - and has a catch block for IOException.&lt;/p&gt;  &lt;p&gt;So, what would &lt;em&gt;you&lt;/em&gt; expect this to print? With the code we&amp;#39;ve got in Eduasync so far, we get this:&lt;/p&gt;  &lt;div class="code"&gt;Caught arbitrary exception: System.AggregateException: One or more errors occurred. ---&amp;gt; System.IO.IOException: I/O error occurred.    &lt;br /&gt;...     &lt;br /&gt;Result: 10&lt;/div&gt;  &lt;p&gt;If you run the same code against the async CTP, you get this:&lt;/p&gt;  &lt;div class="code"&gt;Caught IOException: System.IO.IOException: I/O error occurred.    &lt;br /&gt;...     &lt;br /&gt;Result: 5 &lt;/div&gt;  &lt;p&gt;Hmm... we&amp;#39;re not behaving as per the CTP, and we&amp;#39;re not behaving as we&amp;#39;d really expect the normal synchronous code to behave.&lt;/p&gt;  &lt;p&gt;The first thing to work out is which boundary we should be fixing. In this case, the problem is between the async method and the task we&amp;#39;re awaiting, so the code we need to fix is TaskAwaiter&amp;lt;T&amp;gt;.&lt;/p&gt;  &lt;h3&gt;Handling AggregateException in TaskAwaiter&amp;lt;T&amp;gt;&lt;/h3&gt;  &lt;p&gt;Before we can fix it, we need to work out what&amp;#39;s going on. The stack trace I hid before actually show this reasonably clearly, with this section:&lt;/p&gt;  &lt;div class="code"&gt;at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled Exceptions)    &lt;br /&gt;at System.Threading.Tasks.Task`1.get_Result()     &lt;br /&gt;at Eduasync.TaskAwaiter`1.GetResult() ...\TaskAwaiter.cs:line 40     &lt;br /&gt;at Eduasync.Program.&amp;lt;FetchOrDefaultAsync&amp;gt;d__2.MoveNext() ...\Program.cs:line 37 &lt;/div&gt;  &lt;p&gt;So AggregateException is being thrown by Task&amp;lt;T&amp;gt;.Result, which we&amp;#39;re calling from TaskAwaiter&amp;lt;T&amp;gt;.GetResult(). The documentation for &lt;a href="http://msdn.microsoft.com/en-us/library/dd321468.aspx"&gt;Task&amp;lt;T&amp;gt;.Result&lt;/a&gt; isn&amp;#39;t actually terribly revealing here, but the fact that &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.exception.aspx"&gt;Task&amp;lt;T&amp;gt;.Exception&lt;/a&gt; is of type &lt;a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx"&gt;AggregateException&lt;/a&gt; is fairly revealing.&lt;/p&gt;  &lt;p&gt;Basically, the Task Parallel Library is built with the idea of multiple exceptions in mind - whereas our async method isn&amp;#39;t.&lt;/p&gt;  &lt;p&gt;Now the team in Microsoft &lt;em&gt;could&lt;/em&gt; have decided that really you should catch AggregateException and iterate over all the exceptions contained inside the exception, handling each of them separately. However, in &lt;em&gt;most&lt;/em&gt; cases that isn&amp;#39;t really practical - because in &lt;em&gt;most&lt;/em&gt; cases there will only be one exception (if any) and all that looping is relatively painful. They decided to simply extract the &lt;em&gt;first&lt;/em&gt; exception from the AggregateException within a task, and throw that instead.&lt;/p&gt;  &lt;p&gt;We can do that ourselves in TaskAwaiter&amp;lt;T&amp;gt;, like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; task.Result;     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Statement"&gt;catch&lt;/span&gt; (AggregateException aggregate)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (aggregate.InnerExceptions.Count &amp;gt; 0)     &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;span class="InlineComment"&gt;// Loses the proper stack trace. Oops. For workarounds, see&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// See http://bradwilson.typepad.com/blog/2008/04/small-decisions.html&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt; aggregate.InnerExceptions[0];     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;else&lt;/span&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;span class="InlineComment"&gt;// Nothing better to do, really...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;As you can tell from the comment, we end up losing the stack trace using this code. I don&amp;#39;t know exactly how the stack trace is preserved in the real Async CTP, but it is. I suspect this is done in a relatively obscure way at the moment - it&amp;#39;s possible that for .NET 5, there&amp;#39;ll be a cleaner way that all code can take advantage of.&lt;/p&gt;  &lt;p&gt;This code is also pretty ugly, catching the exception only to rethrow it. We can check whether or not the task has faulted using &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.status.aspx"&gt;Task&amp;lt;T&amp;gt;.Status&lt;/a&gt; and extract the AggregateException using &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.exception.aspx"&gt;Task&amp;lt;T&amp;gt;.Exception&lt;/a&gt; instead of forcing it to be thrown and catching it. We&amp;#39;ll see an example of that in a minute.&lt;/p&gt;  &lt;p&gt;With our new code in place, we can catch the IOException in our async code very easily.&lt;/p&gt;  &lt;h3&gt;What if I want all the exceptions?&lt;/h3&gt;  &lt;p&gt;In certain circumstances it really makes sense to collect multiple exceptions. This is particularly true when you&amp;#39;re waiting for multiple tasks to complete, e.g. with TaskEx.WhenAll in the Async CTP. This caused me a certain amount of concern for a while, but when Mads came to visit in late 2010 and we talked it over, we realized we could use the compositional nature of Task&amp;lt;T&amp;gt; and the convenience of TaskCompletionSource to implement an extension method preserving all the exceptions.&lt;/p&gt;  &lt;p&gt;As we&amp;#39;ve seen, when a task is awaited, its AggregateException is unwrapped, and the first exception rethrown. So if we create a &lt;em&gt;new&lt;/em&gt; task which adds an &lt;em&gt;extra&lt;/em&gt; layer of wrapping and make our code await that instead, only the extra layer will be unwrapped by the task awaiter, leaving the original AggregateException. To come up with a new task which &amp;quot;looks like&amp;quot; an existing task, we can simply create a TaskCompletionSource, add a continuation to the original task, and return the completion source&amp;#39;s task as the wrapper. When the continuation fires we&amp;#39;ll set the appropriate result on the completion source - cancellation, an exception, or the successful result.&lt;/p&gt;  &lt;p&gt;You may expect that we&amp;#39;d have to create a new AggregateException ourselves - but TaskCompletionSource.SetException will already do this for us. This makes it &lt;em&gt;looks&lt;/em&gt; like the code below isn&amp;#39;t performing any wrapping at all, but remember that Task&amp;lt;T&amp;gt;.Exception is already an AggregateException, and calling TaskCompletionSource.SetException will wrap it in &lt;em&gt;another&lt;/em&gt; AggregateException. Here&amp;#39;s the extension method in question:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WithAllExceptions&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; Task&amp;lt;T&amp;gt; task)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; TaskCompletionSource&amp;lt;T&amp;gt; tcs = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;();     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; task.ContinueWith(ignored =&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;span class="Statement"&gt;switch&lt;/span&gt; (task.Status)     &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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Canceled:     &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.SetCanceled();     &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;span class="Statement"&gt;break&lt;/span&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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.RanToCompletion:     &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(task.Result);     &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;span class="Statement"&gt;break&lt;/span&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;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Faulted:     &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;span class="InlineComment"&gt;// SetException will automatically wrap the original AggregateException&lt;/span&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;span class="InlineComment"&gt;// in another one. The new wrapper will be removed in TaskAwaiter, leaving&lt;/span&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;span class="InlineComment"&gt;// the original intact.&lt;/span&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; tcs.SetException(task.Exception);     &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;span class="Statement"&gt;break&lt;/span&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;span class="Modifier"&gt;default&lt;/span&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; tcs.SetException(&lt;span class="Keyword"&gt;new&lt;/span&gt; InvalidOperationException(&lt;span class="String"&gt;&amp;quot;Continuation called illegally.&amp;quot;&lt;/span&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;span class="Statement"&gt;break&lt;/span&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; });     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; tcs.Task;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Here you can see the cleaner way of reacting to a task&amp;#39;s status - we don&amp;#39;t just try to fetch the result and catch any exceptions; we handle each status individually.&lt;/p&gt;  &lt;p&gt;I don&amp;#39;t know offhand what task scheduler is used for this continuation - it may be that we&amp;#39;d really want to specify the current task scheduler for a production-ready version of this code. However, the core idea is sound.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s easy to &lt;em&gt;use&lt;/em&gt; this extension method within an async method, as shown here:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; AwaitMultipleFailures()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;try&lt;/span&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;span class="Modifier"&gt;await&lt;/span&gt; CauseMultipleFailures().WithAllExceptions();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;catch&lt;/span&gt; (AggregateException e)    &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(&lt;span class="String"&gt;&amp;quot;Caught arbitrary exception: {0}&amp;quot;&lt;/span&gt;, e);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; e.InnerExceptions.Count;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Nothing went wrong, remarkably!&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 0;    &lt;br /&gt;}    &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; CauseMultipleFailures()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Simplest way of inducing multiple exceptions&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Exception[] exceptions = { &lt;span class="Keyword"&gt;new&lt;/span&gt; IOException(), &lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException() };    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; TaskCompletionSource&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; tcs = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; tcs.SetException(exceptions);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; tcs.Task;    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note that this will work perfectly well with the Async CTP and should be fine with the full release as well. I wouldn&amp;#39;t be entirely surprised to find something similar provided by the framework itself by release time, too.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;It&amp;#39;s worth being aware of the impedance mismatch between the TPL and async methods in C# 5, as well as how this mismatch is handled. I dislike the idea of data loss, but I can see why it&amp;#39;s being handled in this way. It&amp;#39;s very much in line with the approach of trying to make asynchronous methods &lt;em&gt;look&lt;/em&gt; like synchronous ones as far as possible.&lt;/p&gt;  &lt;p&gt;We&amp;#39;ll probably look at the compositional nature of tasks again later in the series, but this was one simple example of how transparent it can be - a simple extension method can change the behaviour to avoid the risk of losing exception information when you&amp;#39;re &lt;em&gt;expecting&lt;/em&gt; that multiple things can go wrong.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s worth remembering that this behaviour is very specific to Task and Task&amp;lt;T&amp;gt;, and the awaiter types associated with them. If you&amp;#39;re awaiting other types of expressions, they may behave differently with respect to exceptions.&lt;/p&gt;  &lt;p&gt;Before we leave the topic of exceptions, there&amp;#39;s one other aspect we need to look at - what happens when an exception isn&amp;#39;t &lt;em&gt;observed&lt;/em&gt;...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1795039" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 10: CTP bug - don't combine multiple awaits in one statement...</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/10/eduasync-part-10-ctp-bug-don-t-combine-multiple-awaits-in-one-statement.aspx</link><pubDate>Fri, 10 Jun 2011 21:28:46 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1794539</guid><dc:creator>skeet</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1794539</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1794539</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/10/eduasync-part-10-ctp-bug-don-t-combine-multiple-awaits-in-one-statement.aspx#comments</comments><description>&lt;p&gt;(This post covers project 12 in the &lt;a href="http://eduasync.googlecode.com"&gt;source code&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Last time, we saw what happens when we have multiple await expressions: we end up with multiple potential states in our state machine. That&amp;#39;s all fine, but there&amp;#39;s a known bug in the current CTP which affects the code generated when you have multiple awaits in the same statement. (Lucian Wischik calls these &amp;quot;nested awaits&amp;quot; although I personally don&amp;#39;t really think of one as being nested inside an another.)&lt;/p&gt;  &lt;p&gt;This post is mostly a cautionary tale for those using the CTP and deploying it to production - but it&amp;#39;s also interesting to see the &lt;em&gt;kind&lt;/em&gt; of thing that can go wrong. I&amp;#39;m sure this will all be fixed well before release, and the team are already very aware of it. (I expect it&amp;#39;s been fixed internally for a while. It&amp;#39;s not the kind of bug you&amp;#39;d hold off fixing.)&lt;/p&gt;  &lt;p&gt;Just as a reminder, here&amp;#39;s the code we used last time to demonstrate multiple await expressions:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Code from part 9&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; Sum3ValuesAsyncWithAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task1 = Task.Factory.StartNew(() =&amp;gt; 1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task2 = Task.Factory.StartNew(() =&amp;gt; 2);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task3 = Task.Factory.StartNew(() =&amp;gt; 3);     &lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value1 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value2 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task2;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value3 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task3;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; value1 + value2 + value3;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;To simplify things a bit, let&amp;#39;s reduce it to two tasks. Then as a refactoring, I&amp;#39;m going to perform the awaiting within the summation expression:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; Sum2ValuesAsyncWithAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task1 = Task.Factory.StartNew(() =&amp;gt; 1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task2 = Task.Factory.StartNew(() =&amp;gt; 2);&amp;#160; &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;await&lt;/span&gt; task1 + &lt;span class="Modifier"&gt;await&lt;/span&gt; task2;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So, with the local variables value1 and value2 gone, we &lt;em&gt;might&lt;/em&gt; expect that in the generated state machine, we&amp;#39;d have lost the corresponding fields. But should we, really?&lt;/p&gt;  &lt;p&gt;Think what happens if task1 has completed (and we&amp;#39;ve fetched the results), but task2 hasn&amp;#39;t completed by the time we await it. So we call OnContinue and exit as normal, then keep going when the continuation is invoked.&lt;/p&gt;  &lt;p&gt;At that point we should be ready to return... but we&amp;#39;ve got to use the value returned from task1. We need the result to be stored somewhere, and fields are basically all we&amp;#39;ve got.&lt;/p&gt;  &lt;p&gt;Unfortunately, in the current async CTP we don&amp;#39;t have any of these - we just have two local awaiter result variables. Here&amp;#39;s the decompiled code, stripped of the outer skeleton as normal:&lt;/p&gt;  &lt;div class="code"&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult1 = 0;     &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult2 = 0;     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;switch&lt;/span&gt; (state)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; 1:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; 2:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_Awaiter2Continuation;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;default&lt;/span&gt;:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state != -1)     &lt;br /&gt;&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; task1 = Task.Factory.StartNew(() =&amp;gt; 1);     &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; task2 = Task.Factory.StartNew(() =&amp;gt; 2);     &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;&amp;#160;&amp;#160; awaiter1 = task1.GetAwaiter();     &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter1.IsCompleted)     &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; {     &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; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetAwaiter1Result;     &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; }     &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; state = 1;     &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; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&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; awaiter1.OnCompleted(moveNextDelegate);     &lt;br /&gt;&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; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; state = 0;     &lt;br /&gt;Label_GetAwaiter1Result:     &lt;br /&gt;&amp;#160; awaitResult1 = awaiter1.GetResult();     &lt;br /&gt;&amp;#160; awaiter1 = &lt;font color="#0000cc"&gt;default(&lt;/font&gt;TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;());     &lt;br /&gt;    &lt;br /&gt;&amp;#160; awaiter2 = task2.GetAwaiter();     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter2.IsCompleted)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetAwaiter2Result;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; state = 2;     &lt;br /&gt;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160; awaiter2.OnCompleted(moveNextDelegate);     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;Label_Awaiter2Continuation:     &lt;br /&gt;&amp;#160; state = 0;     &lt;br /&gt;Label_GetAwaiter2Result:     &lt;br /&gt;&amp;#160; awaitResult2 = awaiter2.GetResult();     &lt;br /&gt;&amp;#160; awaiter2 = &lt;font color="#0000cc"&gt;default(&lt;/font&gt;TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;());     &lt;br /&gt;    &lt;br /&gt;&amp;#160; result = awaitResult1 + awaitResult2; &lt;/div&gt;  &lt;p&gt;The first half of the code looks like last time (with the natural adjustments for only having two tasks) - but look at what happens when we&amp;#39;ve fetched the result of task1. We fetch the result into awaitResult1, which is a local variable. We then don&amp;#39;t touch awaitResult1 again unless we reach the end of the code - which will &lt;em&gt;not&lt;/em&gt; happen if awaiter2.IsCompleted returns false. When the method returns, the local variable&amp;#39;s value is lost forever... although it will be reset to 0 next time we re-enter, and nothing in the generated code will detect a problem.&lt;/p&gt;  &lt;p&gt;So depending on the timing of the two tasks, the final result &lt;em&gt;can&lt;/em&gt; be 3 (if the second task has finished by the time it&amp;#39;s checked), or 2 (if we need to add a continuation to task2 instead). This is easy to verify by forcing the tasks to sleep before they return.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;The moral of this post is threefold:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;In general, treat CTP and beta-quality code appropriately: I happened to run into this bug, but I&amp;#39;m sure there are others. &lt;em&gt;This is in no way a criticism of the team. It&amp;#39;s just a natural part of developing a complex feature.&lt;/em&gt; &lt;/li&gt;    &lt;li&gt;To avoid &lt;em&gt;this specific&lt;/em&gt; bug, all you have to do is make sure that all relevant state is safely stored in local variables before any logical occurrence of &amp;quot;await&amp;quot;. &lt;/li&gt;    &lt;li&gt;If you&amp;#39;re ever writing a code generator which needs to store state, remember that that state can include expressions which have only been half evaluated so far. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;For the moment, this is all I&amp;#39;ve got on the generated code. Next time, we&amp;#39;ll start looking at how exceptions are handled, and in particular how the CTP behaviour differs from the implementation we&amp;#39;ve seen so far. After a few posts on exceptions, I&amp;#39;ll start covering some daft and evil things I&amp;#39;ve done with async.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1794539" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 9: generated code for multiple awaits</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/30/eduasync-part-9-generated-code-for-multiple-awaits.aspx</link><pubDate>Mon, 30 May 2011 20:06:10 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793980</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793980</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793980</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/30/eduasync-part-9-generated-code-for-multiple-awaits.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/29/eduasync-part-8-generated-code-from-a-complex-async-method.aspx"&gt;Last time&lt;/a&gt; we looked at a complex async method with nested loops and a single await. This post is the exact opposite - the method is going to look simple, but it will have three await expressions in. If you&amp;#39;re glancing down this post and feel put off by the amount of code, don&amp;#39;t worry - once you&amp;#39;ve got the hang of the pattern, it&amp;#39;s really pretty simple.&lt;/p&gt;  &lt;p&gt;Here&amp;#39;s the async method we&amp;#39;re going to analyze:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; Sum3ValuesAsyncWithAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task1 = Task.Factory.StartNew(() =&amp;gt; 1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task2 = Task.Factory.StartNew(() =&amp;gt; 2);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task3 = Task.Factory.StartNew(() =&amp;gt; 3);     &lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value1 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value2 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task2;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value3 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task3;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; value1 + value2 + value3;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Nice and straightforward: start three tasks, then sum their results. Before we look at the decompiled code, it&amp;#39;s worth noting that writing it this way allows the three (admittedly trivial tasks) to run in parallel. If we&amp;#39;d written it this way instead:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; Sum3ValuesAsyncWithAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// No parallelism...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value1 = &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Factory.StartNew(() =&amp;gt; 1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value2 = &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Factory.StartNew(() =&amp;gt; 2);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value3 = &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Factory.StartNew(() =&amp;gt; 3);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; value1 + value2 + value3;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;... then we&amp;#39;d have waited for the first task to finish before starting the second one, then waited for the second one to complete before we started the third one. That&amp;#39;s appropriate when there are dependencies between your tasks (i.e. you need the result of the first as an input to the second) and it would &lt;em&gt;still&lt;/em&gt; have been asynchronous but when you &lt;em&gt;can&lt;/em&gt; start multiple independent tasks together, that&amp;#39;s generally what you want to do. Don&amp;#39;t forget that this doesn&amp;#39;t just extend to CPU-bound tasks - you might want to launch tasks making multiple web service calls in parallel, before collecting the results.&lt;/p&gt;  &lt;p&gt;As before, I&amp;#39;ll just show the heart of the generated code, without its boiler-plate skeleton. Again, the &lt;a href="http://code.google.com/p/eduasync/source/browse/src/MultiAwaitStateMachine/Program.cs"&gt;full code is available online&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Generated code&lt;/h3&gt;  &lt;div class="code"&gt;&amp;#160; &lt;span class="Statement"&gt;switch&lt;/span&gt; (state)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; 1:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; 2:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_Awaiter2Continuation;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; 3:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_Awaiter3Continuation;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;default&lt;/span&gt;:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state != -1)     &lt;br /&gt;&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; task1 = Task.Factory.StartNew(() =&amp;gt; 1);     &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; task2 = Task.Factory.StartNew(() =&amp;gt; 2);     &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; task3 = Task.Factory.StartNew(() =&amp;gt; 3);     &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;&amp;#160;&amp;#160; awaiter1 = task1.GetAwaiter();     &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter1.IsCompleted)     &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; {     &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; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetAwaiter1Result;     &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; }     &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; state = 1;     &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; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&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; awaiter1.OnCompleted(moveNextDelegate);     &lt;br /&gt;&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; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; state = 0;     &lt;br /&gt;Label_GetAwaiter1Result:     &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult1 = awaiter1.GetResult();     &lt;br /&gt;&amp;#160; awaiter1 = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160; value1 = awaitResult1;     &lt;br /&gt;    &lt;br /&gt;&amp;#160; awaiter2 = task2.GetAwaiter();     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter2.IsCompleted)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetAwaiter2Result;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; state = 2;     &lt;br /&gt;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160; awaiter2.OnCompleted(moveNextDelegate);     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;Label_Awaiter2Continuation:     &lt;br /&gt;&amp;#160; state = 0;     &lt;br /&gt;Label_GetAwaiter2Result:     &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult2 = awaiter2.GetResult();     &lt;br /&gt;&amp;#160; awaiter2 = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160; value2 = awaitResult2;     &lt;br /&gt;    &lt;br /&gt;&amp;#160; awaiter3 = task3.GetAwaiter();     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter3.IsCompleted)     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetAwaiter3Result;     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; state = 3;     &lt;br /&gt;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160; awaiter3.OnCompleted(moveNextDelegate);     &lt;br /&gt;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;Label_Awaiter3Continuation:     &lt;br /&gt;&amp;#160; state = 0;     &lt;br /&gt;Label_GetAwaiter3Result:     &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult3 = awaiter3.GetResult();     &lt;br /&gt;&amp;#160; awaiter3 = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160; value3 = awaitResult3;     &lt;br /&gt;    &lt;br /&gt;&amp;#160; result = value1 + value2 + value3; &lt;/div&gt;  &lt;p&gt;Like last time, I&amp;#39;ll just go through the interesting points this raises, rather than examining it line by line.&lt;/p&gt;  &lt;h3&gt;Switch instead of if&lt;/h3&gt;  &lt;p&gt;In all our previous async methods, we&amp;#39;ve only had three possible states: -1 (finished), 0 (normal), 1 (return from continuation). The generated code always looked something like this to start with:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (state != 1)&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state == -1)&amp;#160; &lt;br /&gt;&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;span class="Statement"&gt;return&lt;/span&gt;;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Execute code before the first await, loop or try&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The comment is somewhat brief here, but the basic idea is that all the code which will &lt;em&gt;only&lt;/em&gt; ever execute the first time (with no continuations) can go here. If there&amp;#39;s a loop that contains an await, then a continuation would have to jump back into that loop, so that code couldn&amp;#39;t be contained within this initial block. (A loop which &lt;em&gt;didn&amp;#39;t&lt;/em&gt; have any awaits in could though.)&lt;/p&gt;  &lt;p&gt;Anyway, this time we don&amp;#39;t have an &amp;quot;if&amp;quot; statement like that - we have a switch. It&amp;#39;s the same idea, but we could be in any of three different states when a continuation is called, depending on which await expression we&amp;#39;re at. The switch statement efficiently branches to the right place for a continuation, and executes the initial code otherwise. The &amp;quot;branch&amp;quot; for state 1 is just to exit the switch statement and continue from there.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s possible that the generated code actually has more levels of indirection than it needs; I don&amp;#39;t know about the details of what&amp;#39;s allowed within an IL switch, but it seems odd to effectively have an &amp;quot;On X goto Y&amp;quot; where Y immediately performs a &amp;quot;goto Z&amp;quot;. If the switch statement could branch immediately to the right label, we&amp;#39;d end up with IL which probably wouldn&amp;#39;t have a hope of being decompiled to C#, but which &lt;em&gt;might&lt;/em&gt; be slightly more efficient. It&amp;#39;s quite likely that the JIT can sort all of that out, of course.&lt;/p&gt;  &lt;p&gt;I tend to actually &lt;em&gt;think&lt;/em&gt; about all of this as if the code that&amp;#39;s really in the &amp;quot;default&amp;quot; case for the switch statement appeared after the switch, and the default case just contained a goto statement to jump to it. The effect would be exactly the same, of course - but it means I have a mental model of the method consisting of a &amp;quot;jump to the right place&amp;quot; phase before an &amp;quot;execute the code&amp;quot; phase. Just because I think of it that way doesn&amp;#39;t mean you have to, of course :)&lt;/p&gt;  &lt;h3&gt;Multiple awaiters and await results&lt;/h3&gt;  &lt;p&gt;There&amp;#39;s room for a bit more optimization in this specific case. We have three awaiters, but they&amp;#39;re all of the same type (TaskAwaiter&amp;lt;int&amp;gt;). Likewise, we have three await results, but they&amp;#39;re all int. (It would be possible to have different awaiter types with the same result type, of course.)&lt;/p&gt;  &lt;p&gt;In the CTP (at least without optimization enabled) we end up with an awaiter / awaitResult pair of variables for each await expression. There&amp;#39;s never more than one await &amp;quot;active&amp;quot; at any one time, so the C# compiler &lt;em&gt;could&lt;/em&gt; generate one awaiter variable per awaiter type, and one result variable per result type. In the common situation where the result is being directly assigned to a &amp;quot;local&amp;quot; variable of the same type within the method, we don&amp;#39;t really need the result variable at all. On the other hand, it&amp;#39;s only a local variable (unlike the awaiter) and it&amp;#39;s quite possible that the JIT can optimize this instead.&lt;/p&gt;  &lt;p&gt;Ultimately it&amp;#39;s entirely reasonable for the C# compiler to be generating suboptimal code at this point in the development cycle. After all, it could be quite easy to introduce bugs due to inappropriate code generation... as we&amp;#39;ll see next time.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Other than the different way of getting to the right place on entry (using a switch instead of an if statement), async methods with multiple await expressions aren&amp;#39;t that hard to follow. Of course when you combine multiple awaits with loops, try/catch, try/finally blocks and any number of other things you might use to complicate the async method, things become tricky - but with the fundamentals covered in this blog series, hopefully you&amp;#39;d be able to cope with the generated code in any reasonable situation. Of course, it&amp;#39;s rare that you&amp;#39;ll &lt;em&gt;need&lt;/em&gt; (or want) to look at the generated code in anything like the detail we have here - but now we&amp;#39;ve looked at it, you don&amp;#39;t need to wonder where the magic happens.&lt;/p&gt;  &lt;p&gt;The next post will be the last one involving the decompiled code, at least for the moment. I&amp;#39;d like to demonstrate a bug in the CTP - mostly to show you how a small change to the async method can trigger the wrong results. I&amp;#39;m absolutely positive it will be fixed before release - probably for the next CTP or beta - but I think it&amp;#39;s interesting to see the &lt;em&gt;sort&lt;/em&gt; of situation which can cause problems.&lt;/p&gt;  &lt;p&gt;After that, we&amp;#39;re going to look at exception handling, before we move into a few odd way of using async - in particular, implementing coroutines and &amp;quot;COMEFROM&amp;quot;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793980" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 8: generated code from a complex async method</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/29/eduasync-part-8-generated-code-from-a-complex-async-method.aspx</link><pubDate>Sun, 29 May 2011 18:30:12 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793930</guid><dc:creator>skeet</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793930</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793930</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/29/eduasync-part-8-generated-code-from-a-complex-async-method.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-7-generated-code-from-a-simple-async-method.aspx"&gt;Last time&lt;/a&gt; we had a really simple async method, and looked at the generated code. Even that took a little while... but in this post I&amp;#39;ll demonstrate some of the intricacies that get involved when the async method is more complex. In particular, this time we have:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A parameter to the async method &lt;/li&gt;    &lt;li&gt;A &amp;quot;using&amp;quot; statement, so we&amp;#39;ll need a finally block &lt;/li&gt;    &lt;li&gt;Two loops &lt;/li&gt;    &lt;li&gt;The possibility of catching an exception generated from await and retrying &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;ve not made it as complicated as I &lt;em&gt;could&lt;/em&gt; have done, mind you - we&amp;#39;ve still only got one await expression. Here&amp;#39;s the async method we&amp;#39;ll be investigating:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; WriteValuesAsyncWithAssistance(&lt;span class="ValueType"&gt;int&lt;/span&gt; loopCount)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Namespace"&gt;using&lt;/span&gt; (TextWriter writer = File.CreateText(&lt;span class="String"&gt;&amp;quot;output.txt&amp;quot;&lt;/span&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;span class="ValueType"&gt;int&lt;/span&gt; sum = 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0; i &amp;lt; loopCount; 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; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; valueFetcher = Task.Factory.StartNew(() =&amp;gt; 1);     &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;span class="Statement"&gt;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; j = 0; j &amp;lt; 3; j++)     &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; &lt;span class="Statement"&gt;try&lt;/span&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;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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Awaiting...&amp;quot;&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value = &lt;span class="Modifier"&gt;await&lt;/span&gt; valueFetcher;     &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; writer.WriteLine(&lt;span class="String"&gt;&amp;quot;Got value {0}&amp;quot;&lt;/span&gt;, value);     &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; sum += value;     &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; &lt;span class="Statement"&gt;break&lt;/span&gt;; &lt;span class="InlineComment"&gt;// Break out of the inner for loop&lt;/span&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;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;span class="Statement"&gt;catch&lt;/span&gt; (Exception)     &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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Oops... retrying&amp;quot;&lt;/span&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;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; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; sum;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Okay, so it&amp;#39;s already reasonably complicated even as a normal method. But it gets nastier when we look at the code generated for it. In particular, this time the decompiled code actually isn&amp;#39;t quite valid C#. I&amp;#39;ll get to that in a minute. I&amp;#39;ve split the rest of this post into several smallish chunks to try to help keep several concerns separated. They&amp;#39;re not particularly pleasantly balanced in terms of size, segue etc... but hopefully they&amp;#39;ll make things simpler.&lt;/p&gt;  &lt;h3&gt;The decompiled code&lt;/h3&gt;  &lt;p&gt;I&amp;#39;m going to ignore the standard skeleton - basically everything you see here is within a try/catch block so that we can call SetException on the builder if necessary, and if we reach the end of the method normally, we&amp;#39;ll call SetResult on the builder using the &amp;quot;result&amp;quot; variable. If you want to see the complete method, &lt;a href="http://code.google.com/p/eduasync/source/browse/src/ComplexStateMachine/Program.cs"&gt;it&amp;#39;s in the source repository&lt;/a&gt;. Here&amp;#39;s the cut down version:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;bool&lt;/span&gt; doFinallyBodies = &lt;span class="Keyword"&gt;true&lt;/span&gt;;    &lt;br /&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; tmpState = state;    &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Effectively a three way switch: 1, -1, 0&lt;/span&gt;    &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (tmpState != 1)    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state == -1)    &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;span class="Statement"&gt;return&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.writer = File.CreateText(&lt;span class="String"&gt;&amp;quot;output.txt&amp;quot;&lt;/span&gt;);    &lt;br /&gt;}    &lt;br /&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; tmpState = state;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (tmpState == 1)    &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;span class="Statement"&gt;goto&lt;/span&gt; Label_ResumePoint;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; sum = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; i = 0;    &lt;br /&gt;&amp;#160; Label_ResumePoint: &lt;span class="InlineComment"&gt;// This shouldn&amp;#39;t quite be here... see below&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (i &amp;lt; loopCount)    &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;span class="InlineComment"&gt;// Not in generated code:&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state == 1)    &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;span class="Statement"&gt;goto&lt;/span&gt; Label_ResumePoint2;    &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;span class="InlineComment"&gt;// Back to generated code&lt;/span&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; valueFetcher = Task.Factory.StartNew(() =&amp;gt; 1);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; j = 0;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Still not in the generated code, and still not quite right... we don&amp;#39;t want the j test here&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Label_ResumePoint2:    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Back to generated code again...&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (j &amp;lt; 3)    &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;span class="Statement"&gt;try&lt;/span&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;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;span class="InlineComment"&gt;// We want Label_ResumePoint to be here really&lt;/span&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; tmpState = 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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (tmpState != 1)    &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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Awaiting...&amp;quot;&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiter = valueFetcher.GetAwaiter();    &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (!awaiter.IsCompleted)    &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; {    &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; state = 1;    &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiter.OnCompleted(moveNextDelegate);    &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&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;&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; }    &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;span class="Statement"&gt;else&lt;/span&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;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; state = 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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult = awaiter.GetResult();    &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; awaiter = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;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; value = awaitResult;    &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; writer.WriteLine(&lt;span class="String"&gt;&amp;quot;Got value {0}&amp;quot;&lt;/span&gt;, value);    &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; sum += value;    &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;span class="Statement"&gt;break&lt;/span&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;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;span class="Statement"&gt;catch&lt;/span&gt; (Exception)    &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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Oops... retrying&amp;quot;&lt;/span&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;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; j++;    &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; i++;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; result = sum;    &lt;br /&gt;}    &lt;br /&gt;&lt;span class="Statement"&gt;finally&lt;/span&gt;    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (doFinallyBodies &amp;amp;&amp;amp; writer != &lt;span class="Keyword"&gt;null&lt;/span&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; writer.Dispose();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now that&amp;#39;s a fair bit of code... but if you were comfortable with the last post, there shouldn&amp;#39;t be much which is surprising. I&amp;#39;m not going to go over every aspect of it - just the surprising twists introduced by the extra complexities of the async method.&lt;/p&gt;  &lt;h3&gt;State and tmpState&lt;/h3&gt;  &lt;p&gt;Okay, let&amp;#39;s start from a point of ignorance: I don&amp;#39;t know why a local variable (tmpState) is introduced to take a copy of the state. My guess is that in some really complex scenarios it either becomes relevant when we want to change the state but also know what the state &lt;em&gt;was&lt;/em&gt;, or if we&amp;#39;re testing the state several times without changing it, it may be quicker to do so having copied it to a local variable. I &lt;em&gt;think&lt;/em&gt; we can pretty much ignore it - I&amp;#39;ve only included it here for completeness.&lt;/p&gt;  &lt;h3&gt;To do finally bodies or not to do finally bodies, that is the question&lt;/h3&gt;  &lt;p&gt;Last time the doFinallyBodies variable was pointless because we didn&amp;#39;t have any finally blocks - this time we do (albeit just the one). It&amp;#39;s implicit due to the &amp;quot;using&amp;quot; statement in the original code, but that&amp;#39;s really just a try/finally. The CreateText call occurs before we really enter into the using statement, which is why it&amp;#39;s before the try block in the decompiled code.&lt;/p&gt;  &lt;p&gt;Broadly speaking, a try/finally block in an async method corresponds to the same try/finally block in the generated code, with one big difference: if we&amp;#39;re leaving the method because we&amp;#39;re just returning having attached a continuation to an awaiter, we &lt;em&gt;don&amp;#39;t&lt;/em&gt; want to execute the finally body. After all, the method is effectively &amp;quot;paused&amp;quot; in the block rather than really exiting the block. So, any time you see an OnCompleted call, you&amp;#39;ll see a &amp;quot;doFinallyBodies = false;&amp;quot; statement... and that flag will be set to true at the start of the method, so that at any other time, exiting the try block will cause the finally body to be executed. We still want the body to execute if there&amp;#39;s an exception, for example. This is the &lt;a href="http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx"&gt;same pattern used by the generated code for iterator blocks&lt;/a&gt;. (That&amp;#39;s extremely unsurprising at the moment, as the code generators share a lot of the code. It&amp;#39;s one bit which &lt;em&gt;will&lt;/em&gt; have to be preserved if the two generators are split though.)&lt;/p&gt;  &lt;h3&gt;Go to where exactly?&lt;/h3&gt;  &lt;p&gt;As I mentioned earlier, we can&amp;#39;t write C# code which exactly represented the generated IL. That&amp;#39;s because when we enter the method in state 1 (i.e. for a continuation) the actual generated IL performs a goto &lt;em&gt;straight into the start of the try block&lt;/em&gt;. You can&amp;#39;t do that in straight C#, which is why I&amp;#39;ve got an ugly double-goto in my representation. It doesn&amp;#39;t make it a 100% accurate representation of the IL, but it&amp;#39;s close enough for our purposes. If you build the async method and look at the generated code in Reflector, you&amp;#39;ll see that it basically shows a jump to the final comment above, just inside the try block. (Reflector &lt;em&gt;actually&lt;/em&gt; shows the label as occurring before the try block, but the branch instruction in the IL really does refer to the first instruction in the try block.)&lt;/p&gt;  &lt;p&gt;Now, you may be wondering why the generated code only jumps to the start of the try block. Why doesn&amp;#39;t it just jump straight to the &amp;quot;await&amp;quot; part? Last time it jumped straight to the &amp;quot;state = 0;&amp;quot; statement, after all... so we might expect it to do the same thing here.&lt;/p&gt;  &lt;p&gt;It turns out that although IL has somewhat more freedom than C# in terms of goto (branch) statements, it&amp;#39;s not entirely free of restrictions. In this case, I believe it&amp;#39;s running up against section 12.4.2.8.2.7 of &lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA-335&lt;/a&gt; (the CLI specification) which states:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;If any target of the branch is within a protected block, except the first instruction of that protected block, the source shall be within the same protected block.&lt;/p&gt;    &lt;p&gt;[...]&lt;/p&gt;    &lt;p&gt;[Note: Code can branch to the first instruction of a protected block, but not into the middle of one. end note]&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For &amp;quot;protected block&amp;quot; we can read &amp;quot;try block&amp;quot; (at least in this case).&lt;/p&gt;  &lt;p&gt;I really &lt;em&gt;shouldn&amp;#39;t&lt;/em&gt; enjoy the fact that even the C# compiler can&amp;#39;t do exactly what it would like to here, but somehow it makes me feel better about the way that the C# language restricts us. It&amp;#39;s possible that anthropomorphizing the C# compiler at all is a bad sign for my mental state, but never mind. It gets even worse if an await expression occurs in a &lt;em&gt;nested&lt;/em&gt; try block - another &amp;quot;if&amp;quot; is required for each level involved.&lt;/p&gt;  &lt;p&gt;The point is that by hook or by crook, when a continuation is invoked, we need to reach the assignment back to state 0, followed by the call to awaiter.GetResult().&lt;/p&gt;  &lt;h3&gt;Why do we go back to state 0?&lt;/h3&gt;  &lt;p&gt;You may have noticed that when we return from a continuation, we set the state to 0 before we call GetResult(). We only ever set to the state to a non-zero value just &lt;em&gt;adding&lt;/em&gt; a continuation, or when we&amp;#39;ve finished (at which point we set it to -1). Therefore it will actually be 0 whenever we call GetResult() on an awaiter. But why? Shouldn&amp;#39;t state 0 mean &amp;quot;we&amp;#39;re just starting the method&amp;quot;? We know that state -1 means &amp;quot;the method has finished&amp;quot; and a positive state is used to indicate where we need to come back to when the continuation is called... so what sense does it make to reuse state 0?&lt;/p&gt;  &lt;p&gt;This bit took me a while to work out. In fact, it had me so stumped that I asked a &lt;a href="http://stackoverflow.com/questions/5027999/c-5-async-ctp-why-is-internal-state-set-to-0-in-generated-code-before-endawai"&gt;question on Stack Overflow about it&lt;/a&gt;. Various theories were presented, but none was entirely satisfactory. At the same time, I mailed &lt;a href="http://blogs.msdn.com/b/madst/"&gt;Mads Torgersen&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/lucian/"&gt;Lucian Wischik&lt;/a&gt; about it. After a while, Lucian got back to me and assured me that this &lt;em&gt;wasn&amp;#39;t&lt;/em&gt; a bug - it was very deliberate, and absolutely required. He didn&amp;#39;t say why though - he challenged me to work it out, just in the knowledge that it was required. The example I eventually came up with was a slightly simpler version of the async method in this post.&lt;/p&gt;  &lt;p&gt;The key is to think of states slightly differently:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;-1: finished &lt;/li&gt;    &lt;li&gt;0: running normally; no special action required &lt;/li&gt;    &lt;li&gt;Anything else: Waiting to get back to a continuation point (or in the process of getting there) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So why must we go back to the &amp;quot;running normally&amp;quot; state as soon as we&amp;#39;ve reached the right point when running a continuation? Well, let&amp;#39;s imagine the flow in a situation like the async method shown, but where instead of just creating a trivial task, we&amp;#39;d started one which could fail, and does... but hasn&amp;#39;t finished before we first await it. Ignoring the outer loop and the using statement, we have something like this:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The task is created&lt;/li&gt;    &lt;li&gt;We enter the inner loop&lt;/li&gt;    &lt;li&gt;We write out &amp;quot;Awaiting...&amp;quot; on the console&lt;/li&gt;    &lt;li&gt;We get an awaiter for the task, and check whether it&amp;#39;s completed: it hasn&amp;#39;t, so we add a continuation and return &lt;/li&gt;    &lt;li&gt;The task completes, so we call GetResult() on the awaiter &lt;/li&gt;    &lt;li&gt;GetResult() throws an exception, so we log it in the catch block &lt;/li&gt;    &lt;li&gt;We go back round the inner loop, and want to re-enter step 3 &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now look at the flow control within the decompiled method again, and imagine if we &lt;em&gt;hadn&amp;#39;t&lt;/em&gt; set the state to 0. We&amp;#39;d still be in state 1 when we reached the catch block, so when we got back to the top of the loop, we&amp;#39;d ignore the Console.WriteLine call and not even get a fresh awaiter - we&amp;#39;d end up reusing the same awaiter again. In other words, we&amp;#39;d try to get back to the continuation point.&lt;/p&gt;  &lt;p&gt;To think of it another way: by the time we get back to the call to awaiter.GetResult(), the two possible paths (executing immediately vs adding a continuation, based on the value of awaiter.IsCompleted) have merged and we want to behave &lt;em&gt;exactly the same way&lt;/em&gt; from that point onwards. So naturally we&amp;#39;d want to be in the same state... which is 0 for the synchronous path, as we haven&amp;#39;t had any reason to change state.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;All this complexity, and just with one await expression! As is so often true in computing, it all seems a bit simpler when you can look past it being a wall of code, and break down each lump separately. Hopefully I&amp;#39;ve taken some of the surprises out of the generated code here, although please do leave a comment if anything is still unclear - I&amp;#39;ll try to update the post if so.&lt;/p&gt;  &lt;p&gt;Next time we&amp;#39;ll look at an async method which is generally simpler, but which has three await expressions.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793930" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 7: generated code from a simple async method</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-7-generated-code-from-a-simple-async-method.aspx</link><pubDate>Fri, 20 May 2011 18:21:02 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793538</guid><dc:creator>skeet</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793538</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793538</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-7-generated-code-from-a-simple-async-method.aspx#comments</comments><description>&lt;p&gt;In &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-6-using-the-infrastructure-manually.aspx"&gt;part 6&lt;/a&gt; we tried to come up with a &amp;quot;manual&amp;quot; translation of a very simple async method. This time we&amp;#39;ll see what the compiler really generates.&lt;/p&gt;  &lt;p&gt;As a reminder, here&amp;#39;s the async method in question:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; ReturnValueAsyncWithAssistance()&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; 5);&amp;#160; &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;await&lt;/span&gt; task;&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Whereas our manual code still ended up with a single method (admittedly involving a lambda expression), the generated code is split into the method itself (which ends up being quite small), and a whole extra class representing a &lt;em&gt;state machine&lt;/em&gt;.&lt;/p&gt;  &lt;h3&gt;The &amp;quot;stub&amp;quot; method&lt;/h3&gt;  &lt;p&gt;We looked at a similar translation before, but didn&amp;#39;t really explain it. This time let&amp;#39;s take a closer look:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; ReturnValueAsyncWithStateMachine()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; StateMachine stateMachine = &lt;span class="Keyword"&gt;new&lt;/span&gt; StateMachine(0);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; stateMachine.moveNextDelegate = stateMachine.MoveNext;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; stateMachine.builder = AsyncTaskMethodBuilder&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Create();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; stateMachine.MoveNext();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; stateMachine.builder.Task;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note that I&amp;#39;ve renamed all the variables and the generated type itself to be valid C# identifiers with useful names.&lt;/p&gt;  &lt;p&gt;This is pretty much a minimal stub from an async method. If the async method took parameters, each parameter value would end up being copied into a field in the state machine - but other than that, this is what all async methods end up looking like. (Void async methods just won&amp;#39;t return the builder&amp;#39;s task at the end.)&lt;/p&gt;  &lt;p&gt;The method doesn&amp;#39;t have much work to do:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It creates a new instance of the state machine, passing in an initial state of 0. (I&amp;#39;d expect this constructor parameter to be removed by release - it&amp;#39;ll &lt;em&gt;always&lt;/em&gt; be 0, after all.) &lt;/li&gt;    &lt;li&gt;It creates a new Action delegate instance corresponding to the MoveNext method in the state machine. This is always passed to awaiters as the continuation - by using a field in the state machine, we can avoid creating a new Action instance each time we call OnCompleted. &lt;/li&gt;    &lt;li&gt;It creates a new AsyncTaskMethodBuilder which the state machine uses to set the result and/or exception, and which exposes a task we can return to the caller. &lt;/li&gt;    &lt;li&gt;It calls MoveNext() to synchronously: this will execute at least as far as the first &amp;quot;await&amp;quot; before returning, and may get further than that if the awaited tasks have completed before the await expression. &lt;/li&gt;    &lt;li&gt;It returns the Task&amp;lt;int&amp;gt; from the builder. By this point there &lt;em&gt;may&lt;/em&gt; already be a result, if all the await expressions had already completed. In real async methods, most of the time the returned Task or Task&amp;lt;T&amp;gt; will represent an &lt;em&gt;ongoing&lt;/em&gt; task which the state machine will keep track of. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Obviously, all the smarts are in the state machine...&lt;/p&gt;  &lt;h3&gt;The state machine (completed)&lt;/h3&gt;  &lt;p&gt;Here&amp;#39;s the complete code of the generated state machine, as of the second CTP of the async feature.&lt;/p&gt;  &lt;div class="code"&gt;[CompilerGenerated]    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; StateMachine     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Fields representing local variables&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Fields representing awaiters&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; awaiter;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Fields common to all async state machines&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; builder;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; state;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Action moveNextDelegate;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; StateMachine(&lt;span class="ValueType"&gt;int&lt;/span&gt; state)     &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;span class="InlineComment"&gt;// Pointless: will always be 0. Expect this to be removed from later builds.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.state = state;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; MoveNext()     &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;span class="ValueType"&gt;int&lt;/span&gt; result;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning disable 0219 &lt;span class="InlineComment"&gt;// doFinallyBodies is never used&lt;/span&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;span class="ValueType"&gt;bool&lt;/span&gt; doFinallyBodies = &lt;span class="Keyword"&gt;true&lt;/span&gt;;     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning restore     &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;span class="Statement"&gt;if&lt;/span&gt; (state != 1)     &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (state != -1)     &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; task = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; 5);     &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; awaiter = task.GetAwaiter();     &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; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter.IsCompleted)     &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; {     &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetResult;     &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; }     &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; state = 1;     &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; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiter.OnCompleted(moveNextDelegate);     &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; &lt;span class="Statement"&gt;return&lt;/span&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;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 = 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Label_GetResult:     &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;span class="ValueType"&gt;int&lt;/span&gt; awaitResult = awaiter.GetResult();     &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; awaiter = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;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; result = awaitResult;     &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;span class="Statement"&gt;catch&lt;/span&gt; (Exception e)     &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; state = -1;     &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; builder.SetException(e);     &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;span class="Statement"&gt;return&lt;/span&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; state = -1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; builder.SetResult(result);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Obsolete: will be removed from later builds.&lt;/span&gt;     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning disable 0414     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; disposing;     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning restore     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [DebuggerHidden]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Dispose()     &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; disposing = &lt;span class="Keyword"&gt;true&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; MoveNext();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; state = -1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Yes, it&amp;#39;s pretty complicated. Let&amp;#39;s break it down a bit...&lt;/p&gt;  &lt;h3&gt;Unused code&lt;/h3&gt;  &lt;p&gt;Some of the code here is pointless. It&amp;#39;s a side-effect of the fact that for the CTP, which uses the same code for iterator blocks and async methods - that&amp;#39;s why the primary method within the state machine is called MoveNext. So everything below the comment line starting &amp;quot;Obsolete&amp;quot; can be ignored.&lt;/p&gt;  &lt;p&gt;Additionally, in this case we don&amp;#39;t have any finally blocks - so the doFinallyBodies local variable is unused too. Later on we&amp;#39;ll see an example which &lt;em&gt;does&lt;/em&gt; use it, so don&amp;#39;t worry about it for now.&lt;/p&gt;  &lt;h3&gt;Fields and initialization&lt;/h3&gt;  &lt;p&gt;I&amp;#39;ve explained all the fields in the comments, to some extent. Broadly speaking, there are three types of field in async method translations:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Variables for the infrastructure:      &lt;ul&gt;       &lt;li&gt;The state number, used to work out where to jump back into the method when the continuation is called (or on our first call from the stub method) &lt;/li&gt;        &lt;li&gt;The builder, used to communicate with the task returned to the caller, via SetResult and SetException &lt;/li&gt;        &lt;li&gt;The moveNextDelegate, always passed to the OnCompleted method when an awaiter indicates an incomplete task &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;Awaiter variables: each await expression (currently) has its own awaiter variable. (This may be optimized in a later build.) Each one is set back to the type&amp;#39;s default value (e.g. null for a reference type) after use, but we need to maintain this as a field so we can get the result of an awaiter when we return from a continuation. &lt;/li&gt;    &lt;li&gt;&amp;quot;User&amp;quot; variables representing the local variables of the async method. If the method uses language features such as collection initializers, there may be more of these than expected, but basically they&amp;#39;re whatever you&amp;#39;d see as local variables in a normal method. This also includes parameters for the async method, which are copied into the state machine by the stub method. &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Standard skeleton&lt;/h3&gt;  &lt;p&gt;All async methods (well, those returning results) have a standard skeleton for the MoveNext() method. Void async methods differ in the obvious way. You may recognise this as being extremely similar to part of our manually-written method, too:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; MoveNext()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; result; &lt;span class="InlineComment"&gt;// Type varies based on result type&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;try&lt;/span&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;span class="InlineComment"&gt;// Method-specific code&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;catch&lt;/span&gt; (Exception e)     &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; state = -1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; builder.SetException(e);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state = -1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; builder.SetResult(result);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Hopefully this doesn&amp;#39;t need much explanation: while catching Exception is normally a bad idea, it&amp;#39;s appropriate here, so that it can be rethrown in the caller&amp;#39;s context (or detected without being rethrown). Obviously the method-specific code in the middle needs to make sure that we only reach the bottom of the method in the case where we&amp;#39;re really done - if it ever calls OnCompleted, it needs to return directly rather than falling through to this code.&lt;/p&gt;  &lt;h3&gt;Actual method-specific code...&lt;/h3&gt;  &lt;p&gt;Phew, we&amp;#39;ve finally got to the bit which varies depending on the async method we&amp;#39;re dealing with. Fortunately now that we&amp;#39;ve removed all the extraneous code, it&amp;#39;s easier to see what&amp;#39;s going on. I&amp;#39;ve added some comments for clarity:&lt;/p&gt;  &lt;div class="code"&gt;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state != 1)    &lt;br /&gt;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (state != -1)    &lt;br /&gt;&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; &lt;span class="InlineComment"&gt;// Code before the first await expression&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; task = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; 5);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Boiler-plate for the first part of an await&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiter = task.GetAwaiter();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (awaiter.IsCompleted)    &lt;br /&gt;&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; &lt;span class="Statement"&gt;goto&lt;/span&gt; Label_GetResult;    &lt;br /&gt;&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; state = 1;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; awaiter.OnCompleted(moveNextDelegate);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;    &lt;br /&gt;&amp;#160; }    &lt;br /&gt;&amp;#160; &lt;span class="InlineComment"&gt;// Boiler-plate for the second part of an await&lt;/span&gt;    &lt;br /&gt;&amp;#160; state = 0;    &lt;br /&gt;Label_GetResult:    &lt;br /&gt;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; awaitResult = awaiter.GetResult();    &lt;br /&gt;&amp;#160; awaiter = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160; &lt;span class="InlineComment"&gt;// Code after the await (return, basically)&lt;/span&gt;    &lt;br /&gt;&amp;#160; result = awaitResult; &lt;/div&gt;  &lt;p&gt;Now the state machine for our async method can be in any of three states at the start/end of MoveNext():&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;-1: the method has already completed (possibly with an exception). (It&amp;#39;s unclear how we&amp;#39;d end up getting back into the state machine at this point, but the generated code makes sure it just returns immediately.) &lt;/li&gt;    &lt;li&gt;0: The initial state &lt;em&gt;- &lt;/em&gt;this is also used just before calling GetResult() for situations where we&amp;#39;ve not needed to use a continuation. I&amp;#39;ll go into this slight oddity in another post :) &lt;/li&gt;    &lt;li&gt;1: We&amp;#39;re waiting to be called back by the awaiter. When the continuation is executed, we want to jump straight to &amp;quot;Label_GetResult&amp;quot; so we can fetch the result and continue with the rest of the method. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I suggest you look at the code path taken by the above code if you start in each of those states - convince yourself that when we exit the method, we&amp;#39;ll be in an appropriate state, whether it&amp;#39;s normally or via a continuation.&lt;/p&gt;  &lt;p&gt;Even within this code, we can see boilerplate material: any time you reach an await expression in an async method, the compiler will generate code like the middle section, to get the awaiter, then either skip to the &amp;quot;get result&amp;quot; part or add a continuation. The fiddly bit is really getting your head round how the code flow works, but hopefully as there are relatively few states in play here, it&amp;#39;s not too bad.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;This was a very long post for such a short async method. However, now that we&amp;#39;ve sorted out how it all hangs together, we should be able to look at more complicated async methods without looking at things like the obsolete code and the stub method. Next time we&amp;#39;ll see what happens when we introduce loops, catch blocks and finally blocks.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793538" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 6: using the infrastructure manually</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-6-using-the-infrastructure-manually.aspx</link><pubDate>Fri, 20 May 2011 13:36:28 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793530</guid><dc:creator>skeet</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793530</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793530</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/20/eduasync-part-6-using-the-infrastructure-manually.aspx#comments</comments><description>&lt;p&gt;Now that we&amp;#39;ve got the infrastructure for both returning a task from an async method, and awaiting a Task&amp;lt;T&amp;gt;, we&amp;#39;re going to look at what the compiler does for us. I always find that the best way of appreciating a feature like this is to consider what we&amp;#39;d have to do without it. Later on we&amp;#39;re going to see what the C# compiler does in terms of decompiling the actual generated code, but first we&amp;#39;ll look at what we &lt;em&gt;might&lt;/em&gt; do to achieve the same end result, using the same infrastructure.&lt;/p&gt;  &lt;p&gt;Of course, if we were doing all of this manually we might not choose to use the same infrastructure to start with, but I&amp;#39;m not sure that it would end up being &lt;em&gt;much&lt;/em&gt; cleaner anyway.&lt;/p&gt;  &lt;h3&gt;A simple async method&lt;/h3&gt;  &lt;p&gt;First, let&amp;#39;s look at the C# 5 async method we want to emulate. It&amp;#39;s pretty simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; ReturnValueAsyncWithAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; 5);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;await&lt;/span&gt; task;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now obviously we &lt;em&gt;could&lt;/em&gt; just return the task here to start with - the async method isn&amp;#39;t providing any real benefit. But the simplicity is helpful for showing an equivalent. You can always imagine that there&amp;#39;s more going on between awaiting the result of the task and returning our actual result.&lt;/p&gt;  &lt;h3&gt;What do we need to do?&lt;/h3&gt;  &lt;p&gt;Before I include the actual code, let&amp;#39;s consider what we know about the async method execution model:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We&amp;#39;ll create an AsyncTaskMethodBuilder to allow us to return a Task&amp;lt;int&amp;gt;. &lt;/li&gt;    &lt;li&gt;The method will start synchronously, running all the code before the first (and in this case only) await expression in the normal way. &lt;/li&gt;    &lt;li&gt;The awaitable expression will be evaluated, and GetAwaiter() called to get a suitable awaiter value. &lt;/li&gt;    &lt;li&gt;We&amp;#39;ll ask the awaiter whether the awaitable has already completed, using the IsCompleted property      &lt;ul&gt;       &lt;li&gt;If it&amp;#39;s already completed, we get the result by calling GetResult(). We can set the result on the builder, and return the builder&amp;#39;s task. &lt;/li&gt;        &lt;li&gt;Otherwise, create a continuation delegate representing &amp;quot;the rest of the method&amp;quot;. We then return the builder&amp;#39;s task.          &lt;ul&gt;           &lt;li&gt;The continuation has to fetch the result by calling GetResult() on the same awaiter, set the result on the builder, and return. (It&amp;#39;s not returning a Task&amp;lt;T&amp;gt; - the continuation is just an Action.) &lt;/li&gt;         &lt;/ul&gt;       &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;If an exception occurs at any point, whether in the original synchronous call or the continuation, we need to set that exception in the builder, and return (either returning the builder&amp;#39;s task or nothing, depending on the context). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Even &lt;em&gt;describing &lt;/em&gt;it makes it sound significantly worse than the async method. Let&amp;#39;s take a look.&lt;/p&gt;  &lt;h3&gt;Bring on the code!&lt;/h3&gt;  &lt;p&gt;Here&amp;#39;s the manual method in all its glory:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; ReturnValueAsyncWithoutAssistance()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; AsyncTaskMethodBuilder&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; builder = AsyncTaskMethodBuilder&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Create();     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;try&lt;/span&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; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;.Factory.StartNew(() =&amp;gt; 5);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskAwaiter&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; awaiter = task.GetAwaiter();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (!awaiter.IsCompleted)     &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;span class="InlineComment"&gt;// Result wasn&amp;#39;t available. Add a continuation, and return the builder.&lt;/span&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; awaiter.OnCompleted(() =&amp;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;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;span class="Statement"&gt;try&lt;/span&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;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; builder.SetResult(awaiter.GetResult());     &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; &lt;span class="Statement"&gt;catch&lt;/span&gt; (Exception e)     &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; builder.SetException(e);     &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; });     &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;span class="Statement"&gt;return&lt;/span&gt; builder.Task;     &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; &lt;span class="InlineComment"&gt;// Result was already available: proceed synchronously&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; builder.SetResult(awaiter.GetResult());     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;catch&lt;/span&gt; (Exception e)     &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; builder.SetException(e);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; builder.Task;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Ugly, isn&amp;#39;t it? Even so, it&amp;#39;s actually somewhere simpler than the &lt;em&gt;real&lt;/em&gt; autogenerated code, which we&amp;#39;ll see in the next part. Hopefully if you read the code and comments bearing in mind the bullet points above, it should be reasonably easy to see how it works. However:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Currently we&amp;#39;re building a continuation delegate specific to this particular await. Imagine if we had several await expressions. Each would need &amp;quot;the rest of the method&amp;quot; specified as its own delegate, and we&amp;#39;d end up building multiple delegate instances over time. &lt;/li&gt;    &lt;li&gt;It would be a nightmare to handle loops in this way. &lt;/li&gt;    &lt;li&gt;We&amp;#39;ve got repeated code - not a lot in this case, but anything we had between the &amp;quot;await&amp;quot; and the &amp;quot;return&amp;quot; would need to be in both flows. &lt;/li&gt;    &lt;li&gt;You don&amp;#39;t really want to be writing this code by hand anyway, if you can help it. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Having said all of that, it works. Just don&amp;#39;t expect me to write any more complicated async methods this way :)&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;The steps given here are still going to be valid with the compiler-generated code, but they&amp;#39;ll take a slightly different form. Next time we&amp;#39;ll decompile the generated code for the exact same async method, before we move on to look at more complicated cases.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793530" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 5: making Task&lt;T&gt; awaitable</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/17/eduasync-part-5-making-task-lt-t-gt-awaitable.aspx</link><pubDate>Tue, 17 May 2011 19:47:45 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793417</guid><dc:creator>skeet</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793417</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793417</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/17/eduasync-part-5-making-task-lt-t-gt-awaitable.aspx#comments</comments><description>&lt;p&gt;In &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-3-the-shape-of-the-async-method-awaitable-boundary.aspx"&gt;part 3&lt;/a&gt; we looked at what the C# 5 compiler required for you to &amp;quot;await&amp;quot; something. The sample used a class which actually had an instance method called GetAwaiter, but I mentioned that it could also be an extension method.&lt;/p&gt;  &lt;p&gt;In this post, we&amp;#39;ll use that ability to make Task&amp;lt;T&amp;gt; awaitable - at which point we have everything we need to actually see some asynchronous behaviour. Just like the last part, the code here is pretty plain - but by the end of the post we&amp;#39;ll have a full demonstration of asynchrony. I should make it clear that this isn&amp;#39;t absolutely everything we&amp;#39;ll want, but it&amp;#39;s a good start.&lt;/p&gt;  &lt;h3&gt;TaskAwaiter&amp;lt;T&amp;gt;&lt;/h3&gt;  &lt;p&gt;As it happens, I&amp;#39;m using the same type name as the async CTP does for &amp;quot;something which can await a task&amp;quot; - TaskAwaiter. It&amp;#39;s in a different namespace though, and we &lt;em&gt;could&lt;/em&gt; rename it with no ill-effects (unlike AsyncTaskMethodBuilder, for example). Indeed, in an old version of similar code I called this type Garçon - so GetAwaiter would return a waiter, so to speak. (Yes, you can use non-ASCII characters in identifiers in C#. I wouldn&amp;#39;t really advise it though.)&lt;/p&gt;  &lt;p&gt;All the task awaiter needs is a reference to the task that it&amp;#39;s awaiting - it doesn&amp;#39;t need to know anything about the async method which is waiting for it, for example. Task&amp;lt;T&amp;gt; provides everything we need: a property to find out whether it&amp;#39;s completed, another to fetch the result, and the &lt;a href="http://msdn.microsoft.com/en-us/library/dd235663.aspx"&gt;ContinueWith&lt;/a&gt; method to specify a continuation. The last part is particularly important - without that, we&amp;#39;d really have a hard time implementing this efficiently.&lt;/p&gt;  &lt;p&gt;The extension method on Task&amp;lt;T&amp;gt; is trivial:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TaskExtensions     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; TaskAwaiter&amp;lt;T&amp;gt; GetAwaiter&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; Task&amp;lt;T&amp;gt; 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; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; TaskAwaiter&amp;lt;T&amp;gt;(task);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The TaskAwaiter&amp;lt;T&amp;gt; type itself is &lt;em&gt;slightly&lt;/em&gt; less so, but only slightly:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; TaskAwaiter&amp;lt;T&amp;gt;    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Task&amp;lt;T&amp;gt; task;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt; TaskAwaiter(Task&amp;lt;T&amp;gt; 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; &lt;span class="Keyword"&gt;this&lt;/span&gt;.task = task;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted { get { &lt;span class="Statement"&gt;return&lt;/span&gt; task.IsCompleted; } }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action action)    &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; SynchronizationContext context = SynchronizationContext.Current;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskScheduler scheduler = context == &lt;span class="Keyword"&gt;null&lt;/span&gt; ? TaskScheduler.Current    &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; : TaskScheduler.FromCurrentSynchronizationContext();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; task.ContinueWith(ignored =&amp;gt; action(), scheduler);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; T GetResult()    &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;span class="Statement"&gt;return&lt;/span&gt; task.Result;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;IsCompleted is obviously trivial - Task&amp;lt;T&amp;gt; provides us exactly what we need to know. It&amp;#39;s just worth noting that &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.iscompleted.aspx"&gt;IsCompleted&lt;/a&gt; will return true if the task is cancelled, faulted or completed normally - it&amp;#39;s not the same as checking for &lt;em&gt;success&lt;/em&gt;. However, it represents exactly what we want to know here.&lt;/p&gt;  &lt;p&gt;OnCompleted has two very small aspects of interest:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;ContinueWith takes an Action&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; or an Action&amp;lt;Task&amp;gt;, not just an Action. That means we have to create a new delegate to wrap the original continuation. I can&amp;#39;t currently think of any way round this with the current specification, but it&amp;#39;s slightly annoying. If the compiler could work with an OnCompleted(Action&amp;lt;object&amp;gt;) method then we could pass &lt;em&gt;that&lt;/em&gt; into Task&amp;lt;T&amp;gt;.ContinueWith due to contravariance of Action&amp;lt;T&amp;gt;. The compiler could generate an appropriate MoveNext(object) method which just called MoveNext() and stash an Action&amp;lt;object&amp;gt; field instead of an Action field... and do so only if the async method actually required it. I&amp;#39;ll email the team with this as a suggestion - they&amp;#39;ve made other changes with performance in mind, so this is a possibility. Other alternatives:       &lt;ul&gt;       &lt;li&gt;In .NET 5, Task&amp;lt;T&amp;gt; could have ContinueWith overloads accepting Action as a continuation. That would be simpler from the language perspective, but the overload list would become pretty huge. &lt;/li&gt;        &lt;li&gt;I would expect Task&amp;lt;T&amp;gt; to have a &amp;quot;real&amp;quot; GetAwaiter method in .NET 5 rather than the extension method; it could quite easily just return &amp;quot;this&amp;quot;, possibly with some explicitly implemented IAwaiter&amp;lt;T&amp;gt; interface to avoid polluting the normal API. That could then handle the situation more natively. &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;We&amp;#39;re using the current synchronization context if there &lt;em&gt;is&lt;/em&gt; one to schedule the new task. This is the bit that lets continuations keep going on the UI thread for WPF and WinForms apps. If there isn&amp;#39;t a synchronization context, we just use the current scheduler. For months this was incorrect in Eduasync; I was using TaskScheduler.Current in all cases. It&amp;#39;s a subtle difference which has a huge effect on correctness; apologies for the previous inaccuracy. Even the current code is a lot cruder than it could be, but it should be better than it was...&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;GetResult looks and is utterly trivial - it works fine for success cases, but it doesn&amp;#39;t do what we really want if the task has been faulted or cancelled. We&amp;#39;ll improve it in a later part.&lt;/p&gt;  &lt;h3&gt;Let&amp;#39;s see it in action!&lt;/h3&gt;  &lt;p&gt;Between this and the AsyncTaskMethodBuilder we wrote last time, we&amp;#39;re ready to see an end-to-end asynchronous method demo. Here&amp;#39;s the full code - it&amp;#39;s not as trivial as it might be, as I&amp;#39;ve included some diagnostics so we can see what&amp;#39;s going on:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Program     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; DateTimeOffset StartTime = DateTimeOffset.UtcNow;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &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; Log(&lt;span class="String"&gt;&amp;quot;In Main, before SumAsync call&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = SumAsync();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Log(&lt;span class="String"&gt;&amp;quot;In Main, after SumAsync returned&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; result = task.Result;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Log(&lt;span class="String"&gt;&amp;quot;Final result: &amp;quot;&lt;/span&gt; + result);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; SumAsync()     &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; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task1 = Task.Factory.StartNew(() =&amp;gt; { Thread.Sleep(500); &lt;span class="Statement"&gt;return&lt;/span&gt; 10; });     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task2 = Task.Factory.StartNew(() =&amp;gt; { Thread.Sleep(750); &lt;span class="Statement"&gt;return&lt;/span&gt; 5; });     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Log(&lt;span class="String"&gt;&amp;quot;In SumAsync, before awaits&amp;quot;&lt;/span&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;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value1 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; value2 = &lt;span class="Modifier"&gt;await&lt;/span&gt; task2;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Log(&lt;span class="String"&gt;&amp;quot;In SumAsync, after awaits&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; value1 + value2;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Log(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)     &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(&lt;span class="String"&gt;&amp;quot;Thread={0}. Time={1}ms. Message={2}&amp;quot;&lt;/span&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&lt;span class="ValueType"&gt;long&lt;/span&gt;)(DateTimeOffset.UtcNow - StartTime).TotalMilliseconds,     &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; text);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And here&amp;#39;s the result of one run:&lt;/p&gt;  &lt;div class="code"&gt;Thread=1. Time=12ms. Message=In Main, before SumAsync call    &lt;br /&gt;Thread=1. Time=51ms. Message=In SumAsync, before awaits     &lt;br /&gt;Thread=1. Time=55ms. Message=In Main, after SumAsync returned     &lt;br /&gt;Thread=4. Time=802ms. Message=In SumAsync, after awaits     &lt;br /&gt;Thread=1. Time=802ms. Message=Final result: 15 &lt;/div&gt;  &lt;p&gt;So what&amp;#39;s going on?&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We initially log before we even start the async method. We can see that the thread running Main has ID 1. &lt;/li&gt;    &lt;li&gt;Within SumAsync, we start two tasks using Task.Factory.StartNew. Each task just has to sleep for a bit, then return a value. Everything&amp;#39;s hard-coded. &lt;/li&gt;    &lt;li&gt;We log before we await anything: this occurs still on thread 1, because async methods run synchronously at least as far as the first await. &lt;/li&gt;    &lt;li&gt;We hit the first await, and because the first task hasn&amp;#39;t completed yet, we register a continuation on it, and immediately return to Main. &lt;/li&gt;    &lt;li&gt;We log that we&amp;#39;re in Main, still in thread 1. &lt;/li&gt;    &lt;li&gt;When the first await completes, a thread from the thread pool will execute the continuation. (This may well be the thread which executed the first task; I don&amp;#39;t know the behaviour of the task scheduler used in console apps off the top of my head.) This will then hit the second await, which also won&amp;#39;t have finished - so the first continuation completes, having registered a second continuation, this time on the second task. If we changed the Sleep calls within the tasks, we could observe this second await actually not needing to wait for anything. &lt;/li&gt;    &lt;li&gt;When the second continuation fires, we log that fact. Two things to notice:      &lt;ul&gt;       &lt;li&gt;It&amp;#39;s almost exactly 750ms after the earlier log messages. That proves that the two tasks has genuinely been executing in parallel. &lt;/li&gt;        &lt;li&gt;It&amp;#39;s on thread 4. &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;The final log statement occurs immediately after we return from the async method - thread 1 has been blocked on the task.Result property fetch, but when the async method completes, it unblocks and shows the result. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I think you&amp;#39;ll agree that for the very small amount of code we&amp;#39;ve had to write, this is pretty nifty.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;We&amp;#39;ve now implemented enough of the functionality which is usually in AsyncCtpLibrary.dll to investigate what the compiler&amp;#39;s really doing for us. Next time I&amp;#39;ll include a program showing &lt;em&gt;one&lt;/em&gt; option for using the same types within hand-written code... and point out how nasty it is. Then for the next few parts, we&amp;#39;ll look at what the C# 5 compiler does when we let it loose on code like the above... and show why I didn&amp;#39;t just have &amp;quot;int value = await task1 + await task2;&amp;quot; in the sample program.&lt;/p&gt;  &lt;p&gt;If you&amp;#39;ve skimmed through this post reasonably quickly, now would be a good time to go back and make sure you&amp;#39;re &lt;em&gt;really&lt;/em&gt; comfortable with where in this sample our AsyncTaskMethodBuilder is being used, and where TaskAwaiter is being used. We&amp;#39;ve got Task&amp;lt;T&amp;gt; as the core type at both boundaries, but that&amp;#39;s slightly coincidental - the boundaries are still very different, and it&amp;#39;s worth making sure you understand them before you try to wrap your head round the compiler-generated code.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793417" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 4: Filling in AsyncTaskMethodBuilder&lt;T&gt;</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/15/eduasync-part-4-filling-in-asynctaskmethodbuilder-lt-t-gt.aspx</link><pubDate>Sun, 15 May 2011 19:21:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793292</guid><dc:creator>skeet</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793292</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793292</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/15/eduasync-part-4-filling-in-asynctaskmethodbuilder-lt-t-gt.aspx#comments</comments><description>&lt;p&gt;In &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-2-the-shape-of-the-caller-async-method-boundary.aspx"&gt;part 2&lt;/a&gt;, I introduced AsyncVoidMethodBuilder, AsyncTaskMethodBuilder and AsyncTaskMethodBuilder&amp;lt;T&amp;gt;. I showed all the &lt;em&gt;signatures&lt;/em&gt;, but the implementations were basically trivial and non-functional. Today, I&amp;#39;m going to change all of that... at least a bit.&lt;/p&gt;  &lt;p&gt;In particular, by the end of this post we&amp;#39;ll be able to make the following code actually print out 10 as we&amp;#39;d expect:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = Return10Async();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(task.Result);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; Return10Async()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 10;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note that there are no await statements - remember that AsyncTaskMethodBuilder&amp;lt;T&amp;gt; is about the boundary between the caller and the async method. We won&amp;#39;t be actually doing anything genuinely asynchronous today - just filling in a piece of the infrastructure.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;not&lt;/em&gt; going to implement AsyncVoidMethodBuilder or AsyncTaskMethodBuilder, because once you understand how AsyncTaskMethodBuilder&amp;lt;T&amp;gt; works, the others are basically trivial to implement. (Certainly the non-generic AsyncTaskMethodBuilder is too similar to warrant going into; I may potentially revisit AsyncVoidMethodBuilder to investigate its behaviour on exceptions.)&lt;/p&gt;  &lt;p&gt;Just as a reminder, this is what we need our AsyncTaskMethodBuilder&amp;lt;T&amp;gt; struct to look like in terms of its interface:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt; Create();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetException(Exception e);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetResult(T result);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; Task { get; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Frankly, this would be a bit of a pain to implement ourselves... especially if we wanted to do it in a neat way which didn&amp;#39;t introduce a new thread unnecessarily. Fortunately, Parallel Extensions makes it pretty easy.&lt;/p&gt;  &lt;h3&gt;TaskCompletionSource to the rescue!&lt;/h3&gt;  &lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/dd449174.aspx"&gt;TaskCompletionSource&amp;lt;TResult&amp;gt;&lt;/a&gt; type in the framework makes it almost trivial to implement AsyncTaskMethodBuilder&amp;lt;T&amp;gt;. It provides us everything we need - a task, and the ability to specify how it completes, either with an exception or a value. Our initial implementation is really just going to wrap TaskCompletionSource. I suspect the real CTP does &lt;em&gt;slightly&lt;/em&gt; more work, but you can get a remarkably long way with simple wrapping:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt;    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt; source;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt; AsyncTaskMethodBuilder(TaskCompletionSource&amp;lt;T&amp;gt; source)    &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;span class="Keyword"&gt;this&lt;/span&gt;.source = source;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt; Create()    &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;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;());    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetException(Exception e)    &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.SetException(e);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetResult(T result)    &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.SetResult(result);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; Task { get { &lt;span class="Statement"&gt;return&lt;/span&gt; source.Task; } }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;We&amp;#39;ll see how far that takes us - we may need to tweak it a bit, probably around the exception handling. For the moment though, it certainly does everything we need it to. The program runs, and prints out 10 as we&amp;#39;d expect.&lt;/p&gt;  &lt;p&gt;This part of the code is now &lt;em&gt;ready&lt;/em&gt; for asynchrony - even though nothing we&amp;#39;ve done so far actually creates any different threads. If we call SetResult from one thread while another thread is waiting on the task&amp;#39;s result, the waiting thread will be unblocked as we&amp;#39;d expect.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;In some ways I hope you&amp;#39;re disappointed by this, in the same way that looking at the LINQ to Objects implementations can be slightly disappointing. It feels like so much is being given to us for free - the framework already had all this power, so what&amp;#39;s C# 5 really adding to the mix. Well, we&amp;#39;re nearly at the point where I can show you the details of what the compiler&amp;#39;s doing under the hood. That&amp;#39;s where the real power lies, and is why I&amp;#39;m so excited by the feature.&lt;/p&gt;  &lt;p&gt;First though, we need to implement the awaiter pattern for Task&amp;lt;T&amp;gt;. That&amp;#39;s the task of our next post, and then we can complete the picture by decompiling the generated code for some programs using genuine asynchrony.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793292" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 3: the shape of the async method / awaitable boundary</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-3-the-shape-of-the-async-method-awaitable-boundary.aspx</link><pubDate>Fri, 13 May 2011 21:56:14 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793143</guid><dc:creator>skeet</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793143</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793143</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-3-the-shape-of-the-async-method-awaitable-boundary.aspx#comments</comments><description>&lt;p&gt;Last time we looked into the boundary between the caller of an async method and the method itself.&lt;/p&gt;  &lt;p&gt;This time I&amp;#39;m going to show the same sort of &amp;quot;skeleton API&amp;quot; but for &lt;em&gt;awaitable&lt;/em&gt; types. This is at the heart of C# 5&amp;#39;s async feature: within an async method, you can include &amp;quot;await&amp;quot; expressions. You have to await a value - which could be the return value from a method call, or a property, or the value of a variable. The important thing is that the compile-time type of that expression has the right shape.&lt;/p&gt;  &lt;h3&gt;Definition time&lt;/h3&gt;  &lt;p&gt;Consider this code snippet from an async method (separated into two statements for clarity):&lt;/p&gt;  &lt;div class="code"&gt;Task&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; t = &lt;span class="Keyword"&gt;new&lt;/span&gt; WebClient().DownloadStringTaskAsync(url);     &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text = &lt;span class="Modifier"&gt;await&lt;/span&gt; t; &lt;/div&gt;  &lt;p&gt;I wish to define the following terms:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The &lt;em&gt;task&lt;/em&gt; of the await expression is the expression which comes after &amp;quot;await&amp;quot;; in this case it&amp;#39;s just &amp;quot;t&amp;quot;. &lt;/li&gt;    &lt;li&gt;The &lt;em&gt;awaitable type&lt;/em&gt; is the compile-time type of the task. In this case it&amp;#39;s Task&amp;lt;string&amp;gt;. &lt;/li&gt;    &lt;li&gt;The &lt;em&gt;awaiter type&lt;/em&gt; is the compile-time type of the result of calling GetAwaiter() on the task. &lt;/li&gt;    &lt;li&gt;The &lt;em&gt;result type&lt;/em&gt; is the compile-time return type of the awaiter type&amp;#39;s GetResult method. Here it would be string, when using the CTP or any sensible implementation. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Of these, &amp;quot;task&amp;quot; and &amp;quot;awaiter type&amp;quot; are part of the draft specification. &amp;quot;Awaitable type&amp;quot; and &amp;quot;result type&amp;quot; aren&amp;#39;t.)&lt;/p&gt;  &lt;p&gt;Now, the first two are fairly clear from the code above, but the awaiter and result types aren&amp;#39;t. The compiler validates that calling (foo).GetAwaiter() for a task expression &amp;quot;foo&amp;quot; is valid. It doesn&amp;#39;t have to be an instance method - it can be an extension method, and indeed that&amp;#39;s how it&amp;#39;s implemented in the CTP. Unlike the &lt;a href="https://msmvps.com/blogs/jon_skeet/archive/2008/02/29/odd-query-expressions.aspx"&gt;weird things you can do with LINQ query expressions&lt;/a&gt;, GetAwaiter() really does have to be a method call, and the expression can&amp;#39;t just be a type name. Unless you&amp;#39;re &lt;em&gt;trying&lt;/em&gt; to do weird stuff, this is very unlikely to be an issue for you. It&amp;#39;s only oddballs like me who try to push the envelope.&lt;/p&gt;  &lt;p&gt;With the current CTP the awaitable type can&amp;#39;t be &amp;quot;dynamic&amp;quot;, but the aim is for C# 5 to support awaiting dynamic values. I imagine this won&amp;#39;t affect the execution flow significantly though.&lt;/p&gt;  &lt;p&gt;The awaitable type &lt;em&gt;only&lt;/em&gt; has to support the GetAwaiter() method, as we&amp;#39;ve said. The awaiter type has to have the following accessible members (which can&amp;#39;t be extension methods):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;bool IsCompleted { get; } &lt;/li&gt;    &lt;li&gt;void OnCompleted(Action continuation) &lt;/li&gt;    &lt;li&gt;X GetResult() where X defines the result type for the awaiter, and may be void &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The overall type of the await expression is the result type - and it has to be appropriate for any surrounding context. For example, the assignment to the &amp;quot;text&amp;quot; variable will only work in our sample if the result type is &amp;quot;string&amp;quot; or a type with an implicit conversion to string.&lt;/p&gt;  &lt;h3&gt;A simple (non-functional) awaiter&lt;/h3&gt;  &lt;p&gt;The sample code for this post comes from project 5 in the source solution (&lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FSimpleInt32Awaitable"&gt;SimpleInt32Awaitable&lt;/a&gt;); project 4 is similar but with a void result type. Neither project makes any attempt to do any &lt;em&gt;real&lt;/em&gt; awaiting:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Within some other class&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SimpleWaitAsync()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; SimpleInt32Awaitable awaitable = &lt;span class="Keyword"&gt;new&lt;/span&gt; SimpleInt32Awaitable();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; result = &lt;span class="Modifier"&gt;await&lt;/span&gt; awaitable;     &lt;br /&gt;}     &lt;br /&gt;&amp;#160; &lt;br /&gt;...     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; SimpleInt32Awaitable     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; SimpleInt32Awaiter GetAwaiter()     &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;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; SimpleInt32Awaiter();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; SimpleInt32Awaiter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;true&lt;/span&gt;; } }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action continuation)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; GetResult()     &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;span class="Statement"&gt;return&lt;/span&gt; 5;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note that here both the awaitable type and the awaiter type are structs rather than classes; this is not a requirement by any means.&lt;/p&gt;  &lt;h3&gt;What does it all mean?&lt;/h3&gt;  &lt;p&gt;I don&amp;#39;t want to leave this post without &lt;em&gt;any&lt;/em&gt; clue of what all of this is used for.&lt;/p&gt;  &lt;p&gt;Fairly obviously, GetAwaiter() is called to get an awaiter (clever name, huh?) on which some members are called:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;IsCompleted&lt;/strong&gt; is called to determine whether the task has already completed. If it has, we can skip over the next step. &lt;/li&gt;    &lt;li&gt;If the task hasn&amp;#39;t already completed, we want to return very soon rather than waiting - so &lt;strong&gt;OnCompleted&lt;/strong&gt; is calling with a delegate representing the &lt;em&gt;continuation&lt;/em&gt; of the method. The awaiter promises to ensure that the continuation is called when (and only when) the task has completed, possibly with an exception. &lt;/li&gt;    &lt;li&gt;When we know the task has completed (either synchronously or via the continuation), &lt;strong&gt;GetResult&lt;/strong&gt; is called to retrieve the result. Note that even if the method has a void return type, it still has to be called, as the &amp;quot;result&amp;quot; may be that an exception is thrown. &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Awaiters are pretty flexible - which means they can be abused in evil, horrible ways, as we&amp;#39;ll see later on.&lt;/p&gt;  &lt;p&gt;So far we&amp;#39;ve seen the basic shape of both boundaries, and now we can start actually implementing them with real, useful code.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793143" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 2: the shape of the caller / async method boundary</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-2-the-shape-of-the-caller-async-method-boundary.aspx</link><pubDate>Fri, 13 May 2011 19:35:37 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1793135</guid><dc:creator>skeet</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1793135</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1793135</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/13/eduasync-part-2-the-shape-of-the-caller-async-method-boundary.aspx#comments</comments><description>&lt;p&gt;For the first few parts of this blog series, we’re not going to write code which actually does anything useful. We’re looking at the API more than the implementation - the bare necessities to get the code to compile. Remember that we’re working without AsyncCtpLibrary.dll - which of course supplies all the necessary types normally.&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;In this part, we’ll look at the boundary between the caller and the async method itself. Our test code will have a method which does nothing but return - but which is marked with the “async” modifier. The fact that we don’t have an “await” expression in the method causes a compiler warning - which is entirely reasonable, but irrelevant to our particular situation.&lt;/p&gt;  &lt;h3&gt;Three return types, one basic idea&lt;/h3&gt;  &lt;p&gt;Async methods are limited to three different return types:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;void &lt;/li&gt;    &lt;li&gt;Task (non-generic) &lt;/li&gt;    &lt;li&gt;Task&amp;lt;T&amp;gt; (generic for any type T) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Each of these return types needs a very slightly different form of compiler support... but the general principle is the same. I’ll show each of the three different types, but the test code itself remains exactly the same except for the return type of the method and the return statement. (If you’re going to return Task&amp;lt;int&amp;gt;, you need to return an int, etc.)&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;namespace&lt;/span&gt; Eduasync     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Program     &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;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &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; DoNothingAsync();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Warning CS1998 is about a method with no awaits in... exactly what we&amp;#39;re trying to&lt;/span&gt;     &lt;br /&gt;&lt;span class="InlineComment"&gt;// achieve!&lt;/span&gt;     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning disable 1998&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Return type of void, Task or Task&amp;lt;int&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; DoNothingAsync()     &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;span class="InlineComment"&gt;// For Task&amp;lt;int&amp;gt; insert return 0; here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&lt;span class="PreProcessorDirective"&gt;#pragma&lt;/span&gt; warning restore 1998     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;   &lt;br /&gt;If you try to compile this code without anything else, the compiler gives an error like this:&lt;/p&gt;  &lt;div class="code"&gt;Test.cs(14,30): error CS0656: Missing compiler required member &amp;#39;System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create&amp;#39;    &lt;br /&gt;Test.cs(14,30): error CS1993: Cannot find Task-related types. Are you missing a reference to &amp;#39;AsyncCtpLibrary.dll&amp;#39; ? &lt;/div&gt;  &lt;p&gt;   &lt;br /&gt;While you’d get a similar error for the async method / awaitable boundary, this one is more demanding: you have to have exactly the right types available. It isn’t just a matter of &lt;em&gt;any&lt;/em&gt; library providing support for your current situation (in the same way that Edulinq can live in its own namespace and be an alternative for LINQ to Objects without the compiler caring). These are exact types that the compiler relies on. They&amp;#39;re an implementation detail: they can vary between compilers (so Mono could have a different set of types for example, although I doubt that it will, for the sake of binary compatibility) and they&amp;#39;re &lt;em&gt;not&lt;/em&gt; part of the language specification... at least at the moment.&lt;/p&gt;  &lt;p&gt;There are three types required: AsyncVoidMethodBuilder, AsyncTaskMethodBuilder and AsyncTaskMethodBuilder&amp;lt;T&amp;gt;. They correspond (fairly obviously) to the return types of void, Task, and Task&amp;lt;T&amp;gt; respectively.&lt;/p&gt;  &lt;p&gt;They all look &lt;em&gt;largely&lt;/em&gt; the same, but here are my initial &amp;quot;non-implementations&amp;quot;:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Threading.Tasks;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Namespace"&gt;namespace&lt;/span&gt; System.Runtime.CompilerServices     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; AsyncVoidMethodBuilder     &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;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; AsyncVoidMethodBuilder Create()     &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;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AsyncVoidMethodBuilder();     &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; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetException(Exception e) {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetResult() {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; AsyncTaskMethodBuilder     &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;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; AsyncTaskMethodBuilder Create()     &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;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AsyncTaskMethodBuilder();     &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; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetException(Exception e) {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetResult() {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task Task { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;null&lt;/span&gt;; } }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&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;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt; Create()     &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;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AsyncTaskMethodBuilder&amp;lt;T&amp;gt;();     &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; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetException(Exception e) {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; SetResult(T result) {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Task&amp;lt;T&amp;gt; Task { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;null&lt;/span&gt;; } }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(In the Eduasync project these are in separate files and have diagnostic statements in the SetException/SetResult methods. I didn&amp;#39;t want to take up too much space here.)&lt;/p&gt;  &lt;p&gt;Note that these &lt;em&gt;must&lt;/em&gt; be structs. If they&amp;#39;re not, the compiler will complain. All the methods have to have the exact signatures specified, as far as I can tell - except that everything can be internal if you want it to be (so long as your async methods are in the same assembly of course). In practice these are &lt;em&gt;going&lt;/em&gt; to be public, and they are public everywhere in Eduasync.&lt;/p&gt;  &lt;p&gt;With these implementations, you can compile and even run async methods - but you will, of course, end up with a null reference returned from any async method with a return type of Task or Task&amp;lt;T&amp;gt;.&lt;/p&gt;  &lt;p&gt;In case you&amp;#39;re wondering, the code below shows a little taste of how these types are used. It&amp;#39;s from the version of DoNothingAsync which returns a non-generic Task. This is what the compiler replaces our code with:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task DoNothingAsync()    &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;lt;DoNothingAsync&amp;gt;d__0 d__ = &lt;span class="Keyword"&gt;new&lt;/span&gt; &amp;lt;DoNothingAsync&amp;gt;d__0(0);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; d__.&amp;lt;&amp;gt;t__MoveNextDelegate = &lt;span class="Keyword"&gt;new&lt;/span&gt; Action(d__.MoveNext);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; d__.$builder = AsyncTaskMethodBuilder.Create();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; d__.MoveNext();&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; d__.$builder.Task;&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Obviously &amp;lt;DoNothingAsync&amp;gt;d__0 is a compiler-generated type (hence the unspeakable name). I&amp;#39;m not going into the details just yet - that will the topic of several posts in a little while. The main point of this post was just to show you the &lt;em&gt;shape&lt;/em&gt; of what the compiler requires. The Create() method and the Task property are used within the rewritten method; the SetResult() and SetException() methods are used within the generated type (the state machine) to indicate the async method completing.&lt;/p&gt;  &lt;p&gt;Before too long we&amp;#39;ll implement these types properly (which is reasonably straightforward, given help from the BCL).&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;The caller / async method boundary is relatively inflexible. The compiler relies on particular types, and you simply can&amp;#39;t make an async method return a different kind of value, such as your own Future&amp;lt;T&amp;gt; type. The guts of how it works are all hidden from you, unless you try to compile without the right libraries around: while the valid return types are part of the specification, the types used by the compiler aren&amp;#39;t. While this is &lt;em&gt;perhaps&lt;/em&gt; a little unfortunate in a purist sense, it&amp;#39;s not really a big deal. The &amp;quot;consuming&amp;quot; part of the async method (the boundary between the async method and whatever it&amp;#39;s awaiting) is much more flexible, and more interesting. That&amp;#39;s what we&amp;#39;re going to look at next.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1793135" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item><item><title>Eduasync part 1: introduction</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/05/08/eduasync-part-1-introduction.aspx</link><pubDate>Sun, 08 May 2011 20:05:32 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1792841</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1792841</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1792841</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/05/08/eduasync-part-1-introduction.aspx#comments</comments><description>&lt;p&gt;I’ve been waiting to start this blog series for a couple of months. It’s nice to finally get cracking.&lt;/p&gt;  &lt;p&gt;Hopefully some of you have already read some of &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx"&gt;my thoughts around C# 5’s async feature&lt;/a&gt;, mostly written last year. Since that initial flurry of posts, I’ve been pretty quiet, but I’m still really excited about it. Really, &lt;em&gt;really&lt;/em&gt; excited. I’ve given a few talks on it, and I have a few more still to give - and this blog series will partly be complementary to those talks. In particular, there’s a &lt;a href="http://tv.devexpress.com/#AsyncFromScratch;Webinar.tag;1"&gt;DevExpress webcast&lt;/a&gt; which covers most of the same ground, with &lt;em&gt;similar&lt;/em&gt; code. (It was before the CTP refresh, and also before my laptop was stolen in a burglary, so the code here is a rewrite.)&lt;/p&gt;  &lt;h3&gt;Async from a compiler’s point of view&lt;/h3&gt;  &lt;p&gt;Most of this blog series (at least the bits I anticipate at the moment) will deal with what the compiler does with async methods. (I haven’t used async delegates much at all, but I can’t imagine that the machinery is particularly different.)&lt;/p&gt;  &lt;p&gt;As far as I’ve seen, most of the coverage on the web so far has dealt with &lt;em&gt;using&lt;/em&gt; async. That’s natural, logical and entirely proper. Oh, and a bit boring after a while. I like knowing how a feature &lt;em&gt;works&lt;/em&gt; before I go too far using it. This is a personal idiosyncrasy, and if you’re happy just using async with no “under the hood” details, &lt;em&gt;that’s absolutely fine&lt;/em&gt;. It’s probably worth unsubscribing from my blog for a little while, that’s all.&lt;/p&gt;  &lt;p&gt;This can all be seen as pretty similar to my &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx"&gt;Edulinq&lt;/a&gt; series of posts, which is why I’ve called it Eduasync this time.&lt;/p&gt;  &lt;p&gt;My plan is to walk you through what the C# compiler relies on - the types which are currently part of AsyncCtpLibrary.dll, and how it interacts with Task / Task&amp;lt;T&amp;gt; from .NET 4. We’ll then look at the code &lt;em&gt;generated&lt;/em&gt; by the compiler - essentially a state machine - and some of the less obvious aspects of it. I’ll give examples of any bugs I’ve found in the CTP, just for the heck of it - and as a way of checking whether they’re fixed in later versions. (Obviously I’ve let the C#/VB team know about these as I’ve come across them.)&lt;/p&gt;  &lt;p&gt;I’ll assume that you know the &lt;em&gt;basics&lt;/em&gt; of using async - so if you don’t, now would be a good time to look at the numerous resources on the &lt;a href="http://msdn.microsoft.com/en-us/vstudio/gg316360"&gt;Visual Studio Async home page&lt;/a&gt;. There are loads of videos, specs (including the &lt;a href="http://go.microsoft.com/fwlink/?LinkId=204845"&gt;C# spec changes&lt;/a&gt;, most importantly from my point of view)&lt;/p&gt;  &lt;h3&gt;Get the source now&lt;/h3&gt;  &lt;p&gt;There’s already quite a bit of source code (everything I’m &lt;em&gt;currently&lt;/em&gt; planning on writing about, which is almost inevitably less than I’ll &lt;em&gt;actually&lt;/em&gt; end up writing about) on the &lt;a href="http://eduasync.googlecode.com"&gt;Google Code Eduasync project&lt;/a&gt;. This takes a different approach from Edulinq - instead of just a couple of projects (production and tests, basically) I’ve got a separate project for each topic I want to talk about, with pretty minimal code for that topic. The reason for this is to show the evolution of the code - starting off with almost nothing, and progressing until we’ve got an implementation which achieves at least the bare bones important bits of an async system.&lt;/p&gt;  &lt;p&gt;I’ve numbered the projects within the solution, although the assemblies themselves don’t have the same numbers. They all use a default namespace of just Eduasync, and they don’t refer to each other. Each is meant to be self-contained - oh, and there are no references to AsyncCtpLibrary.dll. The whole point is to reimplement that library :) Of course, you&amp;#39;ll still need the &lt;a href="http://go.microsoft.com/fwlink/?LinkId=203690"&gt;CTP&lt;/a&gt; installed to get the compiler changes.&lt;/p&gt;  &lt;p&gt;The Google Code repository will also contain the blog posts eventually, including any diagrams I need to create (such as the one in a minute).&lt;/p&gt;  &lt;h3&gt;The three blocks and two boundaries&lt;/h3&gt;  &lt;p&gt;One of the things I&amp;#39;ve found important to think about in async is the various parts involved. I&amp;#39;ve ended up with a mental model like this:&lt;/p&gt;  &lt;p&gt;&lt;img style="margin:5px 5px 5px 0px;" src="http://eduasync.googlecode.com/hg/posts/AsyncBlocks.png" alt="" /&gt;&lt;/p&gt;  &lt;p&gt;The bits in blue and red are the ones we&amp;#39;re focusing on here: the contents of the async method, and the boundaries between that and the code that calls it, and the tasks (or other awaitable types) that it awaits.&lt;/p&gt;  &lt;p&gt;For most of this series we&amp;#39;re not really going to care much about what the caller does with the result, or how the awaitable object behaves other than in terms of the methods and properties used by the C# 5 compiler. I&amp;#39;ll discuss the flexibility afforded though - and how it &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; extend to the &amp;quot;caller/async&amp;quot; boundary, only the &amp;quot;async/awaitable&amp;quot; boundary.&lt;/p&gt;  &lt;p&gt;Just to give an explicit example of all of this, here&amp;#39;s a simple little program to asynchronously determine the size of the Stack Overflow home page:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Net;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Threading.Tasks;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Program     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Caller (block 1)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; 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; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; sizeTask = DownloadSizeAsync(&lt;span class="String"&gt;&amp;quot;http://stackoverflow.com&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;In Main, after async method call...&amp;quot;&lt;/span&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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Size: {0}&amp;quot;&lt;/span&gt;, sizeTask.Result);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Async method (block 2)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; DownloadSizeAsync(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; url)     &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;span class="Linq"&gt;var&lt;/span&gt; client = &lt;span class="Keyword"&gt;new&lt;/span&gt; WebClient();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Awaitable (block 3)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; awaitable = client.DownloadDataTaskAsync(url);     &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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Starting await...&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;byte&lt;/span&gt;[] data = &lt;span class="Modifier"&gt;await&lt;/span&gt; awaitable;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Finished awaiting...&amp;quot;&lt;/span&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; &lt;span class="Statement"&gt;return&lt;/span&gt; data.Length;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The comments should make it reasonably clear what the blocks in the diagram mean. It&amp;#39;s not ideal in that the first two blocks are basically methods, whereas the third block is an object - but I&amp;#39;ve found that it still makes sense when we&amp;#39;re thinking about the interactions involved at the boundaries. Notably:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;How does the async method create an appropriate value to return to the caller? &lt;/li&gt;    &lt;li&gt;How does the async method interact with the awaitable when it hits an &amp;quot;await&amp;quot; expression? &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We can (and we&amp;#39;re going to) look at these boundaries very separately. We&amp;#39;ll start off with the first bullet, in part two, which will hopefully follow in the next few days.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1792841" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></item></channel></rss>