Async in C#, the Old and the New

HELLO!

I am Stuart Lang You can find me at stu.dev DMs open!

Agenda

  • Introduction to async and how it works
  • A look at the new guidance - do’s & don’ts
  • Some new stuff
    • Async Streams
    • Channels

Why async/await

How does it work?

How does it work?

Compiler generated code

How does it work?

Safe Abstractions Dangerous Abstractions Async/Await “Powerful” Leaky Magic

“It really troubles me how much async, bad async, really bad async we see in the wild” Kathleen Dollard - .NET Rocks! #1143

Link 🔗

Asynchrony is viral - ❌ Bad

Asynchrony is viral - ✅ Good

Async void - ❌ Bad

Async void - ✅ Good

CancellationTokens - ❌ Bad

CancellationTokens - ✅ Good

Using a timeout - ❌ Bad

Using a timeout - ✅ Good

FlushAsync & Dispose - ❌ Bad

FlushAsync & Dispose - ✅ Good

FlushAsync & Dispose - ✅ Good

FlushAsync & Dispose - ✅ Good

async/await vs return Task- ❌ Bad

async/await vs return Task - ✅ Good

Prefer Task.FromResult over Task.Run - ❌ Bad

Prefer Task.FromResult over Task.Run - ✅ Good

Prefer Task.FromResult over Task.Run - ✅ Good

TaskCompletionSource - ❌ Bad

TaskCompletionSource - ✅ Good

Avoid Task.Run for long blocking - ❌ Bad

Avoid Task.Run for long blocking - ✅ Good

Do not use .Wait() or .Result ❌

SynchronizationContext?

How does it work?

How does it work?

Synchronization Context

Synchronization Context

WindowsFormsSynchronizationContext DispatcherSynchronizationContext Default (ThreadPool) SynchronizationContext AspNetSynchronizationContext stu.dev

Synchronization Context

Specific Thread Used to Execute Delegates Exclusive (Delegates Execute One at a Time) WinForms Yes Yes WPF Yes Yes Default No No ASP.NET No Yes

KA-BLAMO!

KA-BLAMO!

ContextFreeTask

vs-threading

.ConfigureAwait(false)

IAsyncEnumerable<T>

The problem

Familiar definition

Familiar definition

IObservable<T> IEnumerable<T> IAsyncEnumerable<T>

Demo - IAsyncEnumerable<T> & Channels

Watch the demo here!

THANKS!

Any questions? You can find me at: stu.dev