Asynchrony in C# 5 Deep Dive
Joe Albahari Asynchronized swimming Beijing Olympics
JOE ALBAHARI www.albahari.com
Asynchronous Programming is the theme of C# 5 (and VB11)
…and Framework 4.5!
New keywords!
(466 new asynchronous “TAP” methods)
We need concurrency.
But how?
Standard soluPon = threading
Explicit: new Thread()... Implicit: BackgroundWorker
Who enjoys debugging mulHthreaded code?
“We’re here to help!”
“Your call is important to us. Please hold the line!”
“Please enter your phone number and press #”
“We’ll call you back”
Callback
20 minutes later…
ConPnuaPon
Sync vs. Async Synchronous call Asynchronous call Caller WAITS for method to complete
Method returns immediately to caller, and executes callback (conPnuaPon) when complete
“Blocking” “Non-‐blocking”
Speakerphone Concurrency True Asynchronous Call Caller manages concurrency Callee manages concurrency
Caller spins up thread Callee may start a thread
– and WAITS on that thread
No callback/conPnuaPon required
Callback/conPnuaPon usually required
Why async? • Beber thread safety
• Less plumbing code
• Can avoid blocking threads (if I/O bound) – Which improves scalability – And keeps the thread pool clean
• Can abstract concurrency
Framework 1.0: APM (IAsyncResult pabern) stream.BeginRead(…….) stream.EndRead(…….) FAIL! Requires therapist
Framework 2.0: EAP webClient.DownloadStringCompleted += …… webClient.DownloadStringAsync(……..) FAIL! Not composable
Framework 4.0: Tasks
string GetWebPage (string uri) { ... ...
}
void Test() { string html = GetWebPage(“...”); Console.WriteLine (html); }
void GetWebPageAsync ( string uri, Action<string> continuation)
{ ... ...
}
void Test() { GetWebPageAsync(“...”, Console.WriteLine);
}
Task<string> GetWebPageAsync (string uri) { ... ... }
Task<TResult> Result property ExcepHon property ConHnueWith() method
Task<TResult> is a value-‐added signaling construct
Tasks deprecate the APM and REAP!
Task<string> GetWebPageAsync (string uri) { ... ...
}
void Test() { GetWebPageAsync(“...”).ContinueWith (task => Console.WriteLine (task.Result)); }
Task<string> GetWebPageAsync (string uri) { ... ...
}
Task Test() { return GetWebPageAsync(“...”).ContinueWith (task => Console.WriteLine (task.Result)); }
string GetWebPage (string uri) { ... ... }
void Test() { for (int i = 0; i < 5; i++) { string html = GetWebPage(“...”); Console.WriteLine (html); } }
Task<string> GetWebPageAsync (string uri) { ... ... }
int _i = 0; void Test() { GetWebPageAsync(“...”).ContinueWith (task => { Console.WriteLine (task.Result); if (++_i < 5) Test(); }); }
ConPnuaPons and imperaPve code don’t mix!
That’s why we need C# language support aka asynchronous funcHons
Demos • LINQPad Demo • VS Project Demo
Hooray!
Framework 4.5:
APM 353 methods REAP 38 methods TAP 466 methods
The TAP deprecates the APM and REAP
C# 1 C# 2 • Generics • Nullable Types • Closures
C# 3 • Lambda Expressions • Query comprehensions • Extension methods
C# 4 • Dynamic Binding • Parallel Programming (CLR)
Parallel Programming
Task Parallel Library
PLINQ
FW 4.0
Latency
Async FuncPons (C# 5)
Rx
vNext
Concurrency
ImperaHve ImperaHve FuncHonal FuncHonal
Thinking asynchronously • Stop thinking in terms of threads!
• Program synchronously, then await instead of wai:ng
• Don’t block (await instead)
• Keep concurrency fine-‐grained & all the way down!
Resources • CTP: download from MS (search “async CTP”)
• MS Async CTP Forum (search “async CTP forum”)
• LINQPad InteracHve Async Tutorial (click Download more samples from LINQPad)