SlideShare a Scribd company logo
1 of 30
WHO WILL BENEFIT FROM THIS
                                          TOPICS                             WHAT YOU’LL LEAVE WITH
    TALK
•     .NET library developers :           • Getting the Right Mental Model   • Knowledge of:

       •   with knowledge of              • Knowing When Not To Use Async       • when to care about
           async/await in C# / VB                                                 optimizing your async
                                          • Avoiding Allocations                  implementations
       •   interested in low-level perf
                                          • Caring About Context                • …and how to do it
       •   that understand this is
           based on the Developer         • Minimizing Suspensions
           Preview
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
}
.method public hidebysig instance void MoveNext() cil managed
                                     {
                                       // Code size       66 (0x42)
                                       .maxstack 2
                                       .locals init ([0] bool '<>t__doFinallyBodies', [1] class [mscorlib]System.Exception '<>t__ex')
                                       .try
                                       {
                                         IL_0000: ldc.i4.1
                                         IL_0001: stloc.0
                                         IL_0002: ldarg.0
                                         IL_0003: ldfld       int32 Program/'<SimpleBody>d__0'::'<>1__state'
public static async Task SimpleBody() {  IL_0008: ldc.i4.m1
   Console.WriteLine("Hello, Async World!"); IL_000d
                                         IL_0009: bne.un.s
                                         IL_000b: leave.s     IL_0041
}                                        IL_000d: ldstr       "Hello, Async World!"
                                         IL_0012: call        void [mscorlib]System.Console::WriteLine(string)
                                         IL_0017: leave.s     IL_002f
.method public hidebysig static class [mscorlib]System.Threading.Tasks.Task SimpleBody() cil managed
                                       }
{                                      catch [mscorlib]System.Exception
  .custom instance void [mscorlib]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() = ( 01 00 00 00 )
                                       {
  // Code size       32 (0x20)           IL_0019: stloc.1
  .maxstack 2                            IL_001a: ldarg.0
  .locals init ([0] valuetype Program/'<SimpleBody>d__0' V_0)
                                         IL_001b: ldc.i4.m1
  IL_0000: ldloca.s    V_0               IL_001c: stfld       int32 Program/'<SimpleBody>d__0'::'<>1__state'
  IL_0002: call        valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder
                                         IL_0021: ldarg.0
                       [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create()
                                         IL_0022: ldflda      valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder
  IL_0007: stfld       valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<SimpleBody>d__0'::'<>t__builder'
                                                                  Program/'<SimpleBody>d__0'::'<>t__builder'
  IL_000c: ldloca.s    V_0               IL_0027: ldloc.1
  IL_000e: call        instance void Program/'<SimpleBody>d__0'::MoveNext() [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException(
                                         IL_0028: call        instance void
  IL_0013: ldloca.s    V_0                                        class [mscorlib]System.Exception)
  IL_0015: ldflda      valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<SimpleBody>d__0'::'<>t__builder'
                                         IL_002d: leave.s     IL_0041
  IL_001a: call        instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task()
                                       }
  IL_001f: ret                         IL_002f: ldarg.0
}                                      IL_0030: ldc.i4.m1
                                       IL_0031: stfld       int32 Program/'<SimpleBody>d__0'::'<>1__state'
                                       IL_0036: ldarg.0
                                       IL_0037: ldflda      valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder
                                                                Program/'<SimpleBody>d__0'::'<>t__builder'
                                       IL_003c: call        instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetResult()
                                       IL_0041: ret
                                     }
Demo
 Async methods
[CompilerGenerated]
private class <SimpleBody>d__0
{
    private int <>1__state;
    public AsyncTaskMethodBuilder <>t__builder;
    public Action <>t__MoveNextDelegate;
    public void MoveNext();
}




<>t__awaiter1.OnCompleted(<>t__MoveNextDelegate);




public static Task SimpleBodyAsync() {
    ...
    d__.<>t__builder = AsyncTaskMethodBuilder.Create();
    ...
    return d__.<>t__builder.Task;
}
TResult result = await FooAsync();   var $awaiter = FooAsync().GetAwaiter();
                                     if (!$awaiter.IsCompleted) {
                                         SAVE_STATE;
                                         $awaiter.OnCompleted(CompletionDelegate);
                                         return;
                                         Label:
                                         RESTORE_STATE;
                                     }
                                     TResult result = $awaiter.GetResult();
public async Task FooAsync()   public async Task<bool> FooAsync()   public async Task<object> FooAsync()
{                              {                                    {
    ... // doesn’t yield           ... // doesn’t yield                 ... // doesn’t yield
    return;                        return true;                         return null;
}                              }                                    }
public override async Task<int> ReadAsync(
    byte [] buffer, int offset, int count, CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    return Read(buffer, offset, count);
}




public static async Task CopyStreamAsync(Stream input, Stream output)
{
    var buffer = new byte[0x1000];
    int numRead;
    while((numRead = await input.ReadAsync(buffer, 0, buffer.Length)) > 0)
    {
        await output.WriteAsync(buffer, 0, numRead);
    }
}
private Task<int> m_lastTask;

public override Task<int> ReadAsync(
  byte [] buffer, int offset, int count,
  CancellationToken cancellationToken)
{
  if (cancellationToken.IsCancellationRequested)
  {
      var tcs = new TaskCompletionSource<int>();
      tcs.SetCanceled();
      return tcs.Task;
  }

    try
    {
          int numRead = this.Read(buffer, offset, count);
          return m_lastTask != null && numRead == m_lastTask.Result ?
              m_lastTask : (m_lastTask = Task.FromResult(numRead));
    }
    catch(Exception e)
    {
        var tcs = new TaskCompletionSource<int>();
        tcs.SetException(e);
        return tcs.Task;
    }
}
Demo
 Manually caching tasks based
 on domain knowledge leads
 to improved performance.
private static ConcurrentDictionary<string,string> s_urlToContents;

public static async Task<string> GetContentsAsync(string url)
{
  string contents;
  if (!s_urlToContents.TryGetValue(url, out contents))
  {
      var response = await new HttpClient().GetAsync(url);
      contents = response.EnsureSuccessStatusCode().Content.ReadAsString();
      s_urlToContents.TryAdd(url, contents);
  }
  return contents;
}
private static ConcurrentDictionary<string,Task<string>> s_urlToContents;

public static Task<string> GetContentsAsync(string url)
{
  Task<string> contents;
  if (!s_urlToContents.TryGetValue(url, out contents))
  {
      contents = GetContentsAsyncInternal(url);
      contents.ContinueWith(t => s_urlToContents.TryAdd(url, t); },
         CancellationToken.None,
         TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuatOptions.ExecuteSynchronously,
         TaskScheduler.Default);
  }
  return contents;
}

private static async Task<string> GetContentsAsyncInternal(string url) {
  var response = await new HttpClient().GetAsync(url);
  return response.EnsureSuccessStatusCode().Content.ReadAsString();
}
Demo
 Cache Task<TResult> instead
 of TResult to avoid
 unnecessary Task allocations.
Demo
User’s app                                              Your library
       async void button1_Click(…)                             async Task DoWorkAsync()
       {                                                       {
           DoWorkAsync().Wait();
           await DoWorkAsync();                                    await Task.Run(…);
                                                                         Task.Run(…).ConfigureAwait(false);
       }                                                           Console.WriteLine("Done task");
                                                               }

                                                               3. Await captures
  1. DoWorkAsync                                                                                2. Task.Run schedules work
                                                          SynchronizationContext and
invoked on UI thread                                                                               to run on thread pool
                              4. UI blocks waiting for   hooks up a continuation to run
                              DoWorkAsync-returned           when task completes
                                 Task to complete
                                                                              5. Task.Run task completes on pool & invokes
            6. UI thread still blocked                                         continuation which Posts back to UI thread
                waiting for async
            operation to complete.
                    Deadlock!              .ConfigureAwait(false) avoids deadlock.
Demo
 Library implementers should
 use ConfigureAwait(false) to
 improve performance and to
 help avoid deadlocks.
Demo
 Modifying ExecutionContext
 sabotages built-in
 optimizations.
public static async Task FooAsync() {     [CompilerGenerated, StructLayout(LayoutKind.Sequential)]
  var dto = DateTimeOffset.Now;           private struct <FooAsync>d__0 : <>t__IStateMachine {
  var dt = dto.DateTime;                    public DateTimeOffset <dto>5__1;
  await Task.Delay(1000);                   public DateTime <dt>5__2;
  Console.WriteLine(dt);                    ...
}                                         }




public static async Task FooAsync() {     [CompilerGenerated, StructLayout(LayoutKind.Sequential)]
  var dt = DateTimeOffset.Now.DateTime;   private struct <FooAsync>d__0 : <>t__IStateMachine {
  await Task.Delay(1000);                   public DateTime <dt>5__2;
  Console.WriteLine(dt);                    ...
}                                         }
Demo
 Async method “locals”
 become fields on a heap-
 allocated class. More locals
 => more fields => bigger
Async methods are not ordinary
methods.

Use them!

But avoid fine-grained async.
Cache tasks when applicable.

Use ConfigureAwait(false) in libraries.

Avoid gratuitous use of ExecutionContext.

Remove unnecessary locals.
The zen of async: Best practices for best performance
The zen of async: Best practices for best performance

More Related Content

What's hot

Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns ReconsideredAlex Miller
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Mikhail Sosonkin
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8Wilson Su
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.UA Mobile
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Wilson Su
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matterDawid Weiss
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassSam Thomas
 
How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerAndrey Karpov
 
Snapshot Testing @ CocoaheadsNL
Snapshot Testing @ CocoaheadsNLSnapshot Testing @ CocoaheadsNL
Snapshot Testing @ CocoaheadsNLLars Lockefeer
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 

What's hot (19)

Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8
 
java sockets
 java sockets java sockets
java sockets
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
 
How Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzerHow Data Flow analysis works in a static code analyzer
How Data Flow analysis works in a static code analyzer
 
Snapshot Testing @ CocoaheadsNL
Snapshot Testing @ CocoaheadsNLSnapshot Testing @ CocoaheadsNL
Snapshot Testing @ CocoaheadsNL
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 

Similar to The zen of async: Best practices for best performance

Async Best Practices
Async Best PracticesAsync Best Practices
Async Best PracticesLluis Franco
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation PrimitivesSynack
 
Understanding the Common Intermediate Language (CIL)
Understanding the Common Intermediate Language (CIL)Understanding the Common Intermediate Language (CIL)
Understanding the Common Intermediate Language (CIL)James Crowley
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗Pofat Tseng
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragmentChiwon Song
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to SwiftElmar Kretzer
 
Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6scuhurricane
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon) Doyun Hwang
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88Mahmoud Samir Fayed
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 

Similar to The zen of async: Best practices for best performance (20)

Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
 
Understanding the Common Intermediate Language (CIL)
Understanding the Common Intermediate Language (CIL)Understanding the Common Intermediate Language (CIL)
Understanding the Common Intermediate Language (CIL)
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 
ASP.NET core
ASP.NET coreASP.NET core
ASP.NET core
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
 
Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon)
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 

More from Microsoft Developer Network (MSDN) - Belgium and Luxembourg

More from Microsoft Developer Network (MSDN) - Belgium and Luxembourg (20)

Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Executive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of ThingsExecutive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of Things
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014
 
Adam azure presentation
Adam   azure presentationAdam   azure presentation
Adam azure presentation
 
release management
release managementrelease management
release management
 
cloud value for application development
cloud value for application developmentcloud value for application development
cloud value for application development
 
Modern lifecycle management practices
Modern lifecycle management practicesModern lifecycle management practices
Modern lifecycle management practices
 
Belgian visual studio launch 2013
Belgian visual studio launch 2013Belgian visual studio launch 2013
Belgian visual studio launch 2013
 
Windows Azure Virtually Speaking
Windows Azure Virtually SpeakingWindows Azure Virtually Speaking
Windows Azure Virtually Speaking
 
Inside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium AppsInside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium Apps
 
TechDays 2013 Developer Keynote
TechDays 2013 Developer KeynoteTechDays 2013 Developer Keynote
TechDays 2013 Developer Keynote
 
Windows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep DiveWindows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep Dive
 
Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0
 
Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!
 
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.jsBuilding SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
 
Deep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage ServicesDeep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage Services
 
Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...
 
Bart De Smet Unplugged
Bart De Smet UnpluggedBart De Smet Unplugged
Bart De Smet Unplugged
 

Recently uploaded

(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
Call Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls GoaCall Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls Goa
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goasexy call girls service in goa
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914Delhi Call girls
 
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...ritikasharma
 
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...rahim quresi
 
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130Suhani Kapoor
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Serviceanamikaraghav4
 
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Apsara Of India
 
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...Apsara Of India
 
Call Girls Agency In Goa 💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...
Call Girls  Agency In Goa  💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...Call Girls  Agency In Goa  💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...
Call Girls Agency In Goa 💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...russian goa call girl and escorts service
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...noor ahmed
 
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...anamikaraghav4
 

Recently uploaded (20)

(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(DIVYA) Dhanori Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
Call Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls GoaCall Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls Goa
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
 
CHEAP Call Girls in Malviya Nagar, (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in  Malviya Nagar, (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in  Malviya Nagar, (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Malviya Nagar, (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914
 
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Khardah ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
 
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...
Science City Kolkata ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sex...
 
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
VIP Call Girls Service Banjara Hills Hyderabad Call +91-8250192130
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
 
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
 
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
 
Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171
 
Goa Call "Girls Service 9316020077 Call "Girls in Goa
Goa Call "Girls  Service   9316020077 Call "Girls in GoaGoa Call "Girls  Service   9316020077 Call "Girls in Goa
Goa Call "Girls Service 9316020077 Call "Girls in Goa
 
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...
5* Hotels Call Girls In Goa {{07028418221}} Call Girls In North Goa Escort Se...
 
Call Girls Agency In Goa 💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...
Call Girls  Agency In Goa  💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...Call Girls  Agency In Goa  💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...
Call Girls Agency In Goa 💚 9316020077 💚 Call Girl Goa By Russian Call Girl ...
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
 
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
 
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...
Call Girls Service Bantala - Call 8250192130 Rs-3500 with A/C Room Cash on De...
 

The zen of async: Best practices for best performance

  • 1.
  • 2. WHO WILL BENEFIT FROM THIS TOPICS WHAT YOU’LL LEAVE WITH TALK • .NET library developers : • Getting the Right Mental Model • Knowledge of: • with knowledge of • Knowing When Not To Use Async • when to care about async/await in C# / VB optimizing your async • Avoiding Allocations implementations • interested in low-level perf • Caring About Context • …and how to do it • that understand this is based on the Developer • Minimizing Suspensions Preview
  • 3. 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 }
  • 4. .method public hidebysig instance void MoveNext() cil managed { // Code size 66 (0x42) .maxstack 2 .locals init ([0] bool '<>t__doFinallyBodies', [1] class [mscorlib]System.Exception '<>t__ex') .try { IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldfld int32 Program/'<SimpleBody>d__0'::'<>1__state' public static async Task SimpleBody() { IL_0008: ldc.i4.m1 Console.WriteLine("Hello, Async World!"); IL_000d IL_0009: bne.un.s IL_000b: leave.s IL_0041 } IL_000d: ldstr "Hello, Async World!" IL_0012: call void [mscorlib]System.Console::WriteLine(string) IL_0017: leave.s IL_002f .method public hidebysig static class [mscorlib]System.Threading.Tasks.Task SimpleBody() cil managed } { catch [mscorlib]System.Exception .custom instance void [mscorlib]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() = ( 01 00 00 00 ) { // Code size 32 (0x20) IL_0019: stloc.1 .maxstack 2 IL_001a: ldarg.0 .locals init ([0] valuetype Program/'<SimpleBody>d__0' V_0) IL_001b: ldc.i4.m1 IL_0000: ldloca.s V_0 IL_001c: stfld int32 Program/'<SimpleBody>d__0'::'<>1__state' IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder IL_0021: ldarg.0 [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() IL_0022: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<SimpleBody>d__0'::'<>t__builder' Program/'<SimpleBody>d__0'::'<>t__builder' IL_000c: ldloca.s V_0 IL_0027: ldloc.1 IL_000e: call instance void Program/'<SimpleBody>d__0'::MoveNext() [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException( IL_0028: call instance void IL_0013: ldloca.s V_0 class [mscorlib]System.Exception) IL_0015: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<SimpleBody>d__0'::'<>t__builder' IL_002d: leave.s IL_0041 IL_001a: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() } IL_001f: ret IL_002f: ldarg.0 } IL_0030: ldc.i4.m1 IL_0031: stfld int32 Program/'<SimpleBody>d__0'::'<>1__state' IL_0036: ldarg.0 IL_0037: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<SimpleBody>d__0'::'<>t__builder' IL_003c: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetResult() IL_0041: ret }
  • 6.
  • 7.
  • 8. [CompilerGenerated] private class <SimpleBody>d__0 { private int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public Action <>t__MoveNextDelegate; public void MoveNext(); } <>t__awaiter1.OnCompleted(<>t__MoveNextDelegate); public static Task SimpleBodyAsync() { ... d__.<>t__builder = AsyncTaskMethodBuilder.Create(); ... return d__.<>t__builder.Task; }
  • 9. TResult result = await FooAsync(); var $awaiter = FooAsync().GetAwaiter(); if (!$awaiter.IsCompleted) { SAVE_STATE; $awaiter.OnCompleted(CompletionDelegate); return; Label: RESTORE_STATE; } TResult result = $awaiter.GetResult();
  • 10. public async Task FooAsync() public async Task<bool> FooAsync() public async Task<object> FooAsync() { { { ... // doesn’t yield ... // doesn’t yield ... // doesn’t yield return; return true; return null; } } }
  • 11. public override async Task<int> ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); } public static async Task CopyStreamAsync(Stream input, Stream output) { var buffer = new byte[0x1000]; int numRead; while((numRead = await input.ReadAsync(buffer, 0, buffer.Length)) > 0) { await output.WriteAsync(buffer, 0, numRead); } }
  • 12. private Task<int> m_lastTask; public override Task<int> ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(); tcs.SetCanceled(); return tcs.Task; } try { int numRead = this.Read(buffer, offset, count); return m_lastTask != null && numRead == m_lastTask.Result ? m_lastTask : (m_lastTask = Task.FromResult(numRead)); } catch(Exception e) { var tcs = new TaskCompletionSource<int>(); tcs.SetException(e); return tcs.Task; } }
  • 13. Demo Manually caching tasks based on domain knowledge leads to improved performance.
  • 14. private static ConcurrentDictionary<string,string> s_urlToContents; public static async Task<string> GetContentsAsync(string url) { string contents; if (!s_urlToContents.TryGetValue(url, out contents)) { var response = await new HttpClient().GetAsync(url); contents = response.EnsureSuccessStatusCode().Content.ReadAsString(); s_urlToContents.TryAdd(url, contents); } return contents; }
  • 15. private static ConcurrentDictionary<string,Task<string>> s_urlToContents; public static Task<string> GetContentsAsync(string url) { Task<string> contents; if (!s_urlToContents.TryGetValue(url, out contents)) { contents = GetContentsAsyncInternal(url); contents.ContinueWith(t => s_urlToContents.TryAdd(url, t); }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuatOptions.ExecuteSynchronously, TaskScheduler.Default); } return contents; } private static async Task<string> GetContentsAsyncInternal(string url) { var response = await new HttpClient().GetAsync(url); return response.EnsureSuccessStatusCode().Content.ReadAsString(); }
  • 16. Demo Cache Task<TResult> instead of TResult to avoid unnecessary Task allocations.
  • 17.
  • 18.
  • 19.
  • 20. Demo
  • 21. User’s app Your library async void button1_Click(…) async Task DoWorkAsync() { { DoWorkAsync().Wait(); await DoWorkAsync(); await Task.Run(…); Task.Run(…).ConfigureAwait(false); } Console.WriteLine("Done task"); } 3. Await captures 1. DoWorkAsync 2. Task.Run schedules work SynchronizationContext and invoked on UI thread to run on thread pool 4. UI blocks waiting for hooks up a continuation to run DoWorkAsync-returned when task completes Task to complete 5. Task.Run task completes on pool & invokes 6. UI thread still blocked continuation which Posts back to UI thread waiting for async operation to complete. Deadlock! .ConfigureAwait(false) avoids deadlock.
  • 22. Demo Library implementers should use ConfigureAwait(false) to improve performance and to help avoid deadlocks.
  • 23.
  • 24. Demo Modifying ExecutionContext sabotages built-in optimizations.
  • 25. public static async Task FooAsync() { [CompilerGenerated, StructLayout(LayoutKind.Sequential)] var dto = DateTimeOffset.Now; private struct <FooAsync>d__0 : <>t__IStateMachine { var dt = dto.DateTime; public DateTimeOffset <dto>5__1; await Task.Delay(1000); public DateTime <dt>5__2; Console.WriteLine(dt); ... } } public static async Task FooAsync() { [CompilerGenerated, StructLayout(LayoutKind.Sequential)] var dt = DateTimeOffset.Now.DateTime; private struct <FooAsync>d__0 : <>t__IStateMachine { await Task.Delay(1000); public DateTime <dt>5__2; Console.WriteLine(dt); ... } }
  • 26. Demo Async method “locals” become fields on a heap- allocated class. More locals => more fields => bigger
  • 27. Async methods are not ordinary methods. Use them! But avoid fine-grained async.
  • 28. Cache tasks when applicable. Use ConfigureAwait(false) in libraries. Avoid gratuitous use of ExecutionContext. Remove unnecessary locals.