Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

.NET 4.5 Async


Published on

A look at some of the complexities of .NET 4.5 Async

Published in: Technology
  • Be the first to comment

.NET 4.5 Async

  1. 1. .NET 4.5 Async 6th Feb 2013 – 9am Robert MacLean - @rmaclean Proudly sponsored by
  2. 2. Introduction Presenter: Robert MacLean Goal: Give you enough information on async to go away and start being productive Not on .NET 4.5? No issue – I have special content for you! Thanks, Stephen Toub (Microsoft) for some content
  3. 3. Demo: Manual create a system with tasks
  4. 4. Demo highlights Task – been around since .NET 4 Lots of awesome tricks, like continuations Pro: Makes it really easy to work with thread Con: Lots of manual config & boilerplate code On .NET 4: TASKS FOR EVERYTHING!
  5. 5. Where does async come from? Microsoft saw the task use, similar to what we just did and thought “Can’t we make this easier to do?” Introduce syntactic sugar which lets us write code easily, and under the covers it converts it to a state machine
  6. 6. Demo: Using async
  7. 7. Demo highlights Two new modifiers Async decorate the method with it tells compiler async stuff will happen Await tells the state machine where to handle continuations unwraps the result of the task can await any thing returns Task or using ICriticalNotifyCompletion Likely done better than you can do it too Best practice, suffix async methods with async. i.e. LogicAsync()
  8. 8. Async modifier constraints Method must return Task, Task<T> or void Cannot be used with a constructor Cannot be used with main entry point i.e. static void Main(params object[] args) No interface support Cannot await inside a catch block Doesn’t work with goto statements
  9. 9. SynchronisationContext “await task;” continues on: Current SynchronizationContext If null, current TaskScheduler For application-level code: This behavior is almost always what you want. For library-level code: This behavior is almost never what you want! Solution: Task.ConfigureAwait(bool) True (default) run on current context/scheduler False continue where awaited task completes
  10. 10. Demo: ConfigureAwait demo
  11. 11. Don’t just async methods, there is a cost! public static void SimpleBody() { Console.WriteLine("Hello, Async World!"); } .method public hidebysig static void SimpleBody() cil managed { .maxstack 8 L_0000: ldstr "Hello, Async World!" L_0005: call void [mscorlib]System.Console::WriteLine(string) L_000a: ret }
  12. 12. Don’t just async methods, there is a cost! public static async Task SimpleBodyAsync() { Console.WriteLine("Hello, Async World!"); } .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task SimpleBodyAsync() cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() .maxstack 2 .locals init ( [0] valuetype Program/<SimpleBodyAsync>d__0 d__, [1] valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder builder) L_0000: ldloca.s d__ L_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder [mscorlib] System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() L_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/<SimpleBodyAsync>d__0::<>t__builder L_000c: ldloca.s d__ L_000e: ldc.i4.m1 L_000f: stfld int32 Program/<SimpleBodyAsync>d__0::<>1__state L_0014: ldloca.s d__ L_0016: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/<SimpleBodyAsync>d__0::<>t__builder L_001b: stloc.1 L_001c: ldloca.s builder L_001e: ldloca.s d__ L_0020: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Start<valuetype Program/<SimpleBodyAsync>d__0>(!!0&) L_0025: ldloca.s d__ L_0027: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/<SimpleBodyAsync>d__0::<>t__builder L_002c: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() L_0031: ret } .method private hidebysig newslot virtual final instance void MoveNext() cil managed { .override [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext .maxstack 2 .locals init ( [0] bool <>t__doFinallyBodies, [1] class [mscorlib]System.Exception <>t__ex) L_0000: ldc.i4.1 L_0001: stloc.0 L_0002: ldstr "Hello, Async World!" L_0007: call void [mscorlib]System.Console::WriteLine(string) L_000c: leave.s L_0025 L_000e: stloc.1 L_000f: ldarg.0 L_0010: ldc.i4.s -2 L_0012: stfld int32 Program/<SimpleBodyAsync>d__0::<>1__state L_0017: ldarg.0 L_0018: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/<SimpleBodyAsync>d__0::<>t__builder L_001d: ldloc.1 L_001e: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException( class [mscorlib]System.Exception) L_0023: leave.s L_0038 L_0025: ldarg.0 L_0026: ldc.i4.s -2 L_0028: stfld int32 Program/<SimpleBodyAsync>d__0::<>1__state L_002d: ldarg.0 L_002e: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/<SimpleBodyAsync>d__0::<>t__builder L_0033: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetResult() L_0038: ret .try L_0000 to L_000e catch [mscorlib]System.Exception handler L_000e to L_0025 }
  13. 13. Async is very smart Async methods are started synchronously There is a fast path which enables them to complete synchronously Saves lots allocations, memory & performance
  14. 14. Best practises Minimize locals that are constructed before await & used after await Use as few awaits as possible – Task.When(Any/All) is a great help Always return Task – only return void if you have no choice Events are an example of that
  15. 15. Demo: Tips & Tricks
  16. 16. Demo highlights Many parts of the .NET Framework now work with Task & thus Async Async can be applied to lambda’s But shouldn’t be Task.Delay is pretty awesome (no more thread.sleep) GetAwaiter allows for anything to be awaited 
  17. 17. Review async/await – new modifiers for code Just syntactic sugar… really smart syntactic sugar Builds on Task – and it’s million options. Use Task when possible!
  18. 18. Questions? Robert MacLean @rmaclean Proudly sponsored by