Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is an excellent catch - and I agree that there is actually a bug in the CTP here. I dug into it and here's what's going on:</p> <p>This is a combination of the CTP implementation of the async compiler transformations, as well as the existing behavior of the TPL (Task Parallel Library) from .NET 4.0+. Here are the factors at play:</p> <ol> <li>The finally body from source is translated into part of a real CLR-finally body. This is desirable for many reasons, one of which is that we can get the CLR to execute it without catching/rethrowing the exception an extra time. This also simplifies our code gen to some degree - simpler code gen results in smaller binaries once compiled, which is definitely desired by many of our customers. :)</li> <li>The overarching <code>Task</code> for the <code>Func(int n)</code> method is a real TPL task. When you <code>await</code> in <code>Consumer()</code>, then the rest of the <code>Consumer()</code> method is actually installed as a continuation off of the completion of the <code>Task</code> returned from <code>Func(int n)</code>.</li> <li>The way the CTP compiler transforms async methods results in a <code>return</code> being mapped to a <code>SetResult(...)</code> call prior to a real return. <code>SetResult(...)</code> boils down to a call to <a href="http://msdn.microsoft.com/en-us/library/dd449176.aspx" rel="noreferrer"><code>TaskCompletionSource&lt;&gt;.TrySetResult</code></a>.</li> <li><code>TaskCompletionSource&lt;&gt;.TrySetResult</code> signals the completion of the TPL task. Instantly enabling its continuations to occur "sometime". This "sometime" may mean on another thread, or in some conditions the TPL is smart and says "um, I might as well just call it now on this same thread".</li> <li>The overarching <code>Task</code> for <code>Func(int n)</code> becomes technically "Completed" right before the finally gets run. This means that code that was awaiting on an async method <em>may</em> run in parallel threads, or even before the finally block.</li> </ol> <p>Considering the overarching <code>Task</code> is supposed to represent the asynchronous state of the method, fundamentally it shouldn't get flagged as completed until at least all the user-provided code has been executed as per the language design. I'll bring this up with Anders, language design team, and compiler devs to get this looked at.</p> <hr> <p><strong>Scope of Manifestation / Severity:</strong></p> <p>You typically won't be bit by this as bad in a WPF or WinForms case where you have some sort of managed message loop going on. The reason why is that the <code>await</code> on <code>Task</code> implementations defer to the <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" rel="noreferrer"><code>SynchronizationContext</code></a>. This causes the async continuations to be queued up on the pre-existing message loop to be run on the same thread. You can verify this by changing your code to run <code>Consumer()</code> in the following way:</p> <pre><code> DispatcherFrame frame = new DispatcherFrame(exitWhenRequested: true); Action asyncAction = async () =&gt; { await Consumer(); frame.Continue = false; }; Dispatcher.CurrentDispatcher.BeginInvoke(asyncAction); Dispatcher.PushFrame(frame); </code></pre> <p>Once run inside the context of the WPF message loop, the output appears as you would expect it:</p> <pre><code>Consumer: before await #1 Func: Begin #1 Func: End #1 Func: Finally #1 Consumer: after await #1 Consumer: before await #2 Func: Begin #2 Func: End #2 Func: Finally #2 Consumer: after await #2 Consumer: after the loop After the wait </code></pre> <hr> <p><strong>Workaround:</strong></p> <p>Alas, the workaround means changing your code to not use <code>return</code> statements inside a <code>try/finally</code> block. I know this really means you lose a lot of elegance in your code flow. You can use async helper methods or helper lambdas to work around this. Personally, I prefer the helper-lambdas because it automatically closes over locals/parameters from the containing method, as well as keeps your relevant code closer.</p> <p><strong>Helper Lambda approach:</strong></p> <pre><code>static async Task&lt;int&gt; Func( int n ) { int result; try { Func&lt;Task&lt;int&gt;&gt; helperLambda = async() =&gt; { Console.WriteLine( " Func: Begin #{0}", n ); await TaskEx.Delay( 100 ); Console.WriteLine( " Func: End #{0}", n ); return 0; }; result = await helperLambda(); } finally { Console.WriteLine( " Func: Finally #{0}", n ); } // since Func(...)'s return statement is outside the try/finally, // the finally body is certain to execute first, even in face of this bug. return result; } </code></pre> <p><strong>Helper Method approach:</strong></p> <pre><code>static async Task&lt;int&gt; Func(int n) { int result; try { result = await HelperMethod(n); } finally { Console.WriteLine(" Func: Finally #{0}", n); } // since Func(...)'s return statement is outside the try/finally, // the finally body is certain to execute first, even in face of this bug. return result; } static async Task&lt;int&gt; HelperMethod(int n) { Console.WriteLine(" Func: Begin #{0}", n); await TaskEx.Delay(100); Console.WriteLine(" Func: End #{0}", n); return 0; } </code></pre> <hr> <p>As a shameless plug: We're hiring in the languages space at Microsoft, and always looking for great talent. Blog entry <a href="http://blogs.msdn.com/b/visualstudio/archive/2011/02/08/visual-studio-is-hiring.aspx" rel="noreferrer">here</a> with the full list of open positions :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload