Using async/await without .NET Framework 4.5

[Update: We've uploaded a new version of Microsoft.Bcl.Async NuGet package. The previous version will not work correctly on Windows Phone 7.1]

Do you want to use await but don’t want to wait until you can target .NET Framework 4.5? The waiting is over and awaiting is about to begin.

Today, we are proud to announce an update to the Async Targeting Pack we had previously released. The previous targeting pack allowed you to use await when targeting .NET Framework 4.0 and Silverlight 5. Our updated targeting pack allows you to use await in Visual Studio 2012 when targeting any of the following platforms (or higher versions):

  • .NET Framework 4.0 (with KB2468871)
  • Silverlight 4
  • Windows Phone 7.5
  • and portable class libraries targeting those platforms

So effectively we added support for Windows Phone 7.5, Silverlight 4, and portable class libraries.

Hang on – isn’t this simply a language feature anyways?

Yes and no. It’s very tempting to think of the new async/await keywords in C# and Visual Basic as pure language features. And to an extent this is true: the compiler has to do some heavy lifting to turn your code into something that can await operations.

With this mindset developers expect to be able to use await as soon as they use Visual Studio 2012 – independent from the .NET platform they are targeting. However, if you consider how most language features are implemented, it becomes quickly clear that this is not a given. Many language constructs require the .NET platform to expose certain APIs in order to support them. For example, extension methods require the ExtensionAttribute and foreach depends on IEnumerable. In the case of await, both languages require Task and some plumbing that make them awaitable.

What do I need for await?

In order to use await you need two components:

  1. Visual Studio 2012
  2. Some specific .NET APIs

In case you are targeting any of our newer platforms (i.e. .NET 4.5 or .NET for Window Store apps) the second point is a no-op – those platforms already have the required APIs. When you target any of the platforms that shipped before Visual Studio 2012, that is .NET Framework 4.0, Silverlight 4, and Windows Phone 7.5, you need to add a NuGet package that provides those APIs.

Note: If you are a phone developer, you are probably aware of the fact that Visual Studio 2012 doesn’t allow you to build phone apps yet – stay tuned. See this post for details.

Before consuming the packages, make sure you've got the NuGet 2.1 or newer installed.

To add a reference to our NuGet Package, right click the project, select “Manage Package References” and search for Microsoft.Bcl.Async. Make sure you selected the “Online” tab on the left hand side and the top left drop down says “Include Prerelease”.

 Of course, you can also install the package via the Package Manager Console by running the following command:

install-package Microsoft.Bcl.Async –pre

Please note this package is marked as prerelease software – that is, there are some rough edges to be expected. We’ve published the known issues here. As usual, we’d like to know when you are having trouble using it. Simply use the comment section under this blog post.

Happy awaiting!

Comments (45)
  1. Necroman says:

    Great, can't wait to test it. Especially the support in Portable Class Libraries is perfect.

  2. Nicholas Blumhardt says:

    This is great news! I used the previous version of the package in a small Silverlight 5 app, and the improvement in code clarity with async was huge.

  3. John Welch says:

    Just to be really picky, foreach doesn't require IEnumerable, just a suitable GetEnumerator() method (section 8.8.4 of the C# language specification).

  4. dsyme says:

    Hey, welcome to the club at last πŸ™‚

    As I'm sure the blog author knows, C# async/await is a version of the F# async language feature (…/dd233250.aspx), which has been available on VS2008, VS2010 and VS2012 since 2007, and can even be used with .NET 2.0 and .NET 3.5.

    But more seriously, it is awesome to see this programming language feature spreading like wildfire. When we first did the feature in F# at Microsoft Research in 2007 (and the Task library by Daan Leijen too around the same time) we had no idea how massively successful it would be and how fast it would spread. I remember presenting it to Mads Torgorsen, Anders and others in 2008 at MSR Cambridge. Then Mads and many others worked on Anders, and it made its way into C# in 2012.  

    I'm extremely glad for the sake of the whole software industry that this feature is spreading so rapidly, thanks to the incredibly hard ongoing work of people like Immo in the Microsoft CLR and language teams.

  5. Daniel Chambers says:

    Thanks guys. It's great to see support for PCL being added!

    A little hiccup I've run into in a .NET 4 project is that if you want to use the async extensions to WebRequest/WebResponse, you need to manually add a reference to System.Net Version, or you get compile errors.

    Also, there seems to be a problem with Resharper and the WebRequest/WebResponse async stuff; Resharper reports compile errors where there aren't any. I've reported it to them here:…/RSRP-332698

  6. Andrey says:

    Thank you!!!!

  7. @John: You are absolutely right. For the sake of simplicity I didn't want to go too deep into how C# enables foreach. I was looking for some simple, and yet well known examples for languages having a dependency on a an API. A better example would probably have been VB XML literal's dependency on XElement.

    @Don: Thanks for the kind words. Since you named me: in fact, all the hard work has been done by the language teams and my BCL colleagues — they deserve all the credit.

    @Daniel: The issue regarding System.Net.dll is a good one. We should add it to the list of known issues. To be fair, this issue is not new. Whenever you are referencing APIs whose surface area dependencies are defined in an assembly that isn't referenced the compilers give you an error telling the assembly that you need to reference.

    The ReSharper issue is an interesting one — thanks for reporting it!

  8. Henrique Clausing says:

    Thanks so much!!

  9. Simone says:

    Hi Immo, a couple of questions since we basically just added support for async test methods in NUnit.

    – We are relying on the presence of the System.Runtime.CompilerServices.AsyncStateMachineAttribute to identify them, does this still hold true here?

    – We are interacting with a thread's SynchronizationContext to handle async void test methods (which normally would not be awaitable). Do async void methods interact with the synchronization context in the same way here as well? (Post, OperationStarted, OperationCompleted)

    Thanks, Simone

  10. Jay B. Harlow says:

    Thank you very much for the Silverlight 4 support! however I have come across a very annoying bug. ConfigureAwait doesn't work in Silverlight 4, nor Silverlight 5:…/configureawait-false-still-continue-on-captured-context-when-using-async-targeting-pack

    This pack & the existing async targeting pack have the same issue in Silverlight 4 and Silverlight 5 respectively!

  11. @Simone:

    Regarding detecting async methods:, the answer is yes. We've provided that type exactly for that purpose, that is detetcing async methods via static analysis.

    Regaring sync context: can you provide more details? What do you mean by "interacting with async void methods". Please shoot me an email at immol at microsoft dot com. Thanks.


    Thanks for reporting the issue via connect. We'll take a look and come back to you there.

  12. @Sgt.Riggs: Thanks for reporting the issue via connect. I just had a quick look and seems like a bug. We'll look into it.

  13. Konamiman says:

    So, will Windows Phone 7 (not 8) development be possible in Visual Studio 2012? That would be really great!

  14. @Konamiman: Yes, for 7.5.

    "The Windows Phone SDK 8.0 is built on top of Visual Studio 2012, and will give you the ability to build applications and games that target both Windows Phone 8 as well as Windows Phone 7.5."

    For more details have at look at this post:…/windows-phone-8-sdk-preview-program-is-now-open.aspx

  15. Valdis Iljuconoks says:

    Das ist fantastisch! πŸ™‚

  16. Eric says:

    It seems not working correctly.

    Here is my test code:

    class Program


    static void Main(string[] args)






    static async void Test()



    Console.WriteLine(await Doo("4"));



    static async Task<string> Doo(string s)



    return s;



    It's output is 1,3,6,4,5,2 (AsyncCTPV3) and 1,3,6,2 (Microsoft.Bcl.Async pre)

    My test was on VS2010 SP1 for both console application and WP7.1 application.

  17. @Eric:

    To me, the behavior differences look like a race condition in your code. In essence, your main method doesn't await the completion of Test(), so it is undefined whether it completes before Console.WriteLine("2") or not. The fact you can consistently repro this is probably simply due to some unrelated implementation specific aspect, such as loading additional files.

    Since you can't use async/await in main, simply move all the code into another method and replace the body of main to only contain a call to that method. In this new method, await the completion of Test and the behavior should be consistent.

  18. GrantDG says:

    I'm not sure this is the correct place to ask this, but I'm at wit's end.

    I am converting WP7 code to use the Microsoft.Bcl.Async, and I have a requirement to set a time-out for Http requests.

    From my reading (more related to the c# 4.5+ features I think), there's samples that use :

      await Task.WhenAny(download, Task.Delay(3000)

    However, in this library Task.WhenAny doesn't exist, nor does Task.Delay

    I also thought of using a CancellationToken, but the DownloadStringTaskAsync extension method doesn't have an overload to take a cancellation token.

    Am I missing something? Is there any way to set a timeout?

  19. @GrantDG: Due to technical restrictions we couldn't expose these methods on Task. You can find WhenAny and Delay on TaskEx. Sorry for that!

  20. @Eric

    Maybe you can compile your project with 'C:WindowsMicrosoft.NETFrameworkv4.0.30319MSBuild.exe'.

  21. I upgraded my WP71 project to VS 2012 and referenced this package. It compiles and it runs but it throws exception MethodAccessException all the time. How to fix this?

    The stack trace looks like this:

    System.MethodAccessException occurred

     Message=Attempt to access the method failed: System.Environment.get_ProcessorCount()


          at System.Delegate.InternalCreateDelegate(Type type, Object firstArgument, MethodInfo method, StackCrawlMark& scm)

          at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method)

          at System.LightupServices.CreateDelegate(Type type, Object instance, MethodInfo method)

          at System.Lightup.CreateMethodAccessor(Type type, String name)

          at System.Lightup.GetMethodAccessor(Delegate& storage, Type type, String name)

          at System.Lightup.GetMethodAccessor[T](Delegate& storage, String name)

          at System.Lightup.TryCall[T](Delegate& storage, String methodName, Int32& returnValue)

          at System.Lightup.TryGet[T](Delegate& storage, String propertyName, Int32& value)

          at System.EnvironmentLightup.TryGetProcessorCount(Int32& count)

          at System.EnvironmentLightup.get_ProcessorCount()

          at System.Threading.PlatformHelper.get_ProcessorCount()

          at System.Threading.CancellationTokenSource..cctor()

          at [more MyApp code]

          at MyApp.App.Initialize()

          at MyApp.App.Application_Launching(Object sender, LaunchingEventArgs e)

          at Microsoft.Phone.Shell.PhoneApplicationService.FireLaunching()

          at Microsoft.Phone.Execution.NativeEmInterop.FireOnLaunching()

  22. Here is another sample of the exception:

    System.MethodAccessException occurred

     Message=Attempt to access the method failed: System.Threading.ExecutionContext.Capture()


          at System.Delegate.InternalCreateDelegate(Type type, Object firstArgument, MethodInfo method, StackCrawlMark& scm)

          at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method)

          at System.LightupServices.CreateDelegate(Type type, Object instance, MethodInfo method)

          at System.Lightup.CreateMethodAccessor(Type type, String name)

          at System.Lightup.GetMethodAccessor(Delegate& storage, Type type, String name)

          at System.Lightup.GetMethodAccessor[T](Delegate& storage, String name)

          at System.Lightup.TryCall[T](Delegate& storage, String methodName, Object& returnValue)

          at System.ExecutionContextLightup.Capture()

          at System.Threading.Tasks.Task.PossiblyCaptureContext(StackCrawlMark& stackMark)

          at System.Threading.Tasks.Task`1..ctor(Func`1 valueSelector, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, StackCrawlMark& stackMark)

          at System.Threading.Tasks.Task`1.StartNew(Task parent, Func`1 function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, StackCrawlMark& stackMark)

          at System.Threading.Tasks.TaskFactory.StartNew[TResult](Func`1 function, CancellationToken cancellationToken)

          at [more MyApp code]

          at Microsoft.Phone.Shell.ApplicationBarItemContainer.FireEventHandler(EventHandler handler, Object sender, EventArgs args)

          at Microsoft.Phone.Shell.ApplicationBarIconButton.ClickEvent()

          at Microsoft.Phone.Shell.ApplicationBarIconButtonContainer.ClickEvent()

          at Microsoft.Phone.Shell.ApplicationBar.OnCommand(UInt32 idCommand)

          at Microsoft.Phone.Shell.Interop.NativeCallbackInteropWrapper.OnCommand(UInt32 idCommand)

  23. It seems that I don't get MethodAccessException on WP8 Emulator only. WP71 Emulator and WP71 device both still have the issue. I can't upgrade to WP8 because I want to support WP71 devices.

  24. Michael says:

    How can I create a task based client in an portable library?

  25. I'm working on a C# Windows Store App. I want some of my logic shared between an existing Windows Phone 7,5 app and this Windows 8 app. I use the portable class library to accomplish that. I always use async/await an would of course also use async/await in the portable class library project. But when I add Microsoft.Bcl.Async to the portable class library (which is referenced by the Windows Store App), the Windows Store App refuse to start. I just get the following error:

    Unable to activate Windows Store app '<someAppGuid>'. The app.exe process started, but the activation request failed with error 'The app didn't start'.

    In the event viewer the following event is recorded:

    Activation of the app <someAppGuid> for the Windows.Launch contract failed with error: The app didn't start..

    Any advice? πŸ™‚

  26. David Kean says:

    @Vladislav What happens if you press F5 to continue the application when you hit these exceptions? Does the application continue to run? It looks like you might be hitting some "first-chance exceptions" that are handled later in the code by our implementation. An easy to test this, is to go to Tools -> Exceptions, and uncheck Thrown next to Common Language Runtime Exceptions and see if you they continue to occur.

    @NielsLBeck: Looks like you might be hitting a known issue. Can you see if an App.Config exists in the Windows Store project? If so, removing it, should fix the problem.

  27. @David: Thanks! Now it works as expected πŸ™‚

  28. Hi David,

    I am also having the same problem as Vladislav with the System.MethodAccessException so turned off Common Language Runtime Exceptions which silences the exception but I still don't believe it is working. The following code is a simple example and this code is running in the context of the OnNavigatedTo override on PhoneApplicationPage:

           protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)




               var syncRequired = await syncService.IsSyncRequired();



    When this code is executed I get the output FOO but I never receive the BAR output, the debugger output shows as follows:


    A first chance exception of type 'System.MethodAccessException' occurred in mscorlib.dll

    If I place a breakpoint on Debug.WriteLine("BAR"); it never breaks. My application continues to run as if nothing the OnNavigatedTo return after the FOO line.

    I am running this on a Nokia Lumia 800 using a 7.1 project with the latest version.


  29. Russell Pooley says:

    Is it possible for this project to be put on Codeplex or something similar so it can be maintained. I am struggling to get this working on Windows Phone 7 but there appears to be no support.

    I appreciate this is a beta but as a developer there is nothing more frustrating than getting a blocking issue and finding that there is no way of solving it.

  30. Lucas says:

    I thought .NET Portable was supported ? I tried many combinations ?

    Could not install package 'Microsoft.Bcl 1.0.11-beta'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.0,Profile=Profile104', but the package does not contain any assembly references that are compatible with that framework. For more information, contact the package author.

  31. @Russel: can you provide more details? What is not working for you?

    @Lucas: although we do support portable class library we don't support it for all the targets. In order to consume our package from portable you need to target .NET Framework 4.0 (with KB2468871), Silverlight 4, Windows Phone 7.5 or any combination of it. Specifically, the package isn't supported on Xbox or Windows Phone 7.0.

  32. Hi Immo,

    I have produced a sample of this problem and in the process of doing it I have figured out why it wasn't working and for the sake of the community I may as well post my resolution here.

    I have an interface that returns a Task<bool> if a file exists.

    In the WinRT world I am retrieving the result from the following method:

    ApplicationData.Current.LocalFolder.ContainsFileAsync which returns a Task<bool>

    In the Windows Phone 7 world I am using the equivalent:


    In the Windows Phone 7 world the FileExists method does not return a Task<bool> it returns bool so I implemented the WP7 version as the following:

              return new Task<bool>(()=>IsolatedStorageFile.GetUserStoreForApplication().FileExists(FileName));

    This is where my problem stems from, the task was returning but I was not getting a result.

    During the process of creating the sample, I had a doh! moment and slapped my forehead.

    For my implementation to work I need to start the task I have created otherwise it will never finish because I haven't started it. Once I changed the implementation to the following it all worked as intended:

               var task = new Task<bool>(()=>IsolatedStorageFile.GetUserStoreForApplication().FileExists(FileName));


               return task;

    My apologies for not figuring this out earlier and hopefully somebody will learn from this. My only question on this would be is my WP7 implementation correct or is there a better way of doing it?

  33. Hi,

    I couldn't believe that I will be able to use async/await in .net 4.0! Thanks a lot for your work!

    As for new updates of it, will I be notified from Visual Studio's update mechanism where there is one available (update) ?

    Again, thanks a lot for this stuff!

  34. Dan says:

    I'm getting this error when I try and add the package to a solution containing portable class library projects that target: WP7.5, Silverlight 4.0 and above and Dot Net 4.0 and above.  The known issues mentions this being a problem for WP7.1 projects but that is definitely not the case here.

    install-package : Could not install package 'Microsoft.Bcl 1.0.11-beta'. You are trying to install this package into a project that targets

    '.NETPortable,Version=v4.0,Profile=Profile104', but the package does not contain any assembly references that are compatible with that framework. For more information, contact

    the package author.

    At line:1 char:1

    + install-package Microsoft.Bcl.Async –pre

    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

       + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException

       + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

  35. Dan says:

    I solved my problem.  Nuget needed to be updated to version 2.1 as PCL's aren't supported in version 2.0

  36. @rpooley: Thanks for coming back. I'd suggest you use TaskEx.FromResult() instead (Why is it not on Task? Well, because we couldn't put it there for technical reasons).

    @King Kikapu: Glad you like it! I don't think VS will prompt you, but you the NuGet package manager dialog will show you when updates are available.

    @Dan: Sorry for the inconvenience, but glad you found the solution.

  37. Suppose I want to compile a Stream subclass into a PCL targeting .NET 4.0 and e.g. .NET for Windows Store apps. For such a PCL, the Stream class does not offer the ReadAsync method. Instead, these methods are only available as extension methods. Is there a clean way to override said method, such that a .NET 4 client can call ReadAsync on a Stream reference pointing to a subclass object?

  38. @andreas_huber69: Unfortunately not. Portable class libraries can't add new APIs to existing types. In those cases, we use extension methods. The only clean way is to ensure that the platforms you are targeting have the APIs you want to use. In your case, targeting .NET 4.5, Phone 8 and Windows Store should do the trick.

  39. @Immo: Thanks for your quick response. IMHO, this is a limitation that should be clear to anyone using async/await on platforms like .NET 4, Windows Phone 7.5, etc.

    BTW, the AsyncExtensions.ReadAsync method calls Stream.BeginRead/EndRead, so as a workaround one could override those methods. Of course, the implementation could still take advantage of async/await:

    // untested code

    public override IAsyncResult BeginRead(byte[] buffer, int offset, int count)


       return this.ReadAsyncCore(buffer, offset, count, CancellationToken.None);


    private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)


       // implementation with await      


    The caveats I see are:

    – A CancellationToken passed to AsyncExtensions.ReadAsync is not observed

    – a (probably small) perf hit due to the additional indirection

  40. Tom says:

    When i want to build every project into the same folder, what do you suggest how to handle the fact that some assembly for the different platforms (Portable, .NET 4, WP7.1) (e.g. Microsoft.Threading.Tasks) have the same name? The last built project will win and overwrite the platform specific assemblies of the other projects.

  41. David Kean [MSFT] says:

    @Tom: In the properties of each reference, change "Copy Local" to false for each version that you don't want to copy to the output folder. Be careful however, you want to make sure that Phone, Silverlight, etc projects get exactly the binary that they built against when they are packaged. ie Phone 7.5 must get System.Runtime, v1.5 and System.Threading.Tasks, v1.5.

  42. Tom says:

    Hm maybe i didnt explain my problem well.  All my projects (Windows Phone, .NET, Windows Store and Portable libraries) build into the same directory.  (something like SubversionRootBinariesDebug)

    For example if i want to create a .NET 4.0 application that references a portable library that targets .NET40, WP7.1, SL4, etc.  Both projects (the .NET 4 application and the portable library) depend on async e.g. on the  System.Runtime.dll assembly. Which dll should i copy to the output? The .NET40 specifc ( or the Portable Library specific ( I think i need both… unfortunatelly they have the same file name, so i can't copy both into the same output folder.

    Another example:

    I have a .NET Application, a WindowsPhone application. Both applications depend on a portable library. All Projects use async and build into the same directory. Which bcl assemblies should i copy to the output? I think i can't solve it because i need different versions of the same assembly in my output directory.

    I have the same problem with this assembly:


    Thats just an example. I would prefer if the bcl assemblies would have different assembly and file names like








    I this case i would have no problem, all async assemblies could be copied to the output and also referenced from the same directory.

  43. Binding issue with C++ project says:

    I am currently using the new async library across a project with a large number of interdependent assemblies, I have had to use assembly binding redirect in each project to get it to compile (as per issue 2 in…/asynctargetingpackkb.aspx).

    The problem I now have is that I consume one of these libraries from a C++/CLR DLL project, it does not actually need to use async but I have the following compilation error:

    2>C:WindowsMicrosoft.NETFrameworkv4.0.30319Microsoft.Common.targets(1578,5): warning MSB3268: The primary reference "ImInterface.dll" could not be resolved because it has an indirect dependency on the framework assembly "System.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0". To resolve this problem, either remove the reference "ImInterface.dll" or retarget your application to a framework version which contains "System.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

    I have added the same app.config file that I have used in all of the C# projects but it does not seem to be having any effect in the C++ project. Do I have to place it in a specific directory or perform any other steps to enable the app.config file to be recognised?



  44. Hello,

    Can you, please, look at…/methodaccessexception-when-using-async-for-wp7-5-version-1-0-12-beta

    It was mentioned here couple of times and is really annoying.

    Thank you in advance for solving it.

    Otherwise it is a great work. Please keep it going!

Comments are closed.

Skip to main content