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.
http://netponto.org 
50ª Reunião Presencial @ LISBOA 
DateTime.Parse(“22-11-2014", new CultureInfo("pt-PT")); 
hashtag #ne...
50ª Reunião Lisboa – 22-11-2014 http://netponto.org 
Async-Await Best Practinces 
in 10 minutes 
Paulo Morgado
Paulo Morgado 
• http://PauloMorgado.NET/ 
• @PauloMorgado 
• http://about.me/PauloMorgado 
• http://www.slideshare.net/Pa...
For goodness’ sake, 
stop using async void!
Async void is only for event handlers 
Principles 
Async void is a “fire-and-forget” mechanism... 
The caller is unable to...
The problem is events. 
They’re not going away.
Async over events 
• Principles 
Callback-based programming, as with events, is hard 
• Guidance 
If the event-handlers ar...
Is it CPU-bound, 
or I/O-bound?
Threadpool 
Principles 
CPU-bound work means things like: LINQ-over-objects, or big iterations, or computational inner loo...
Don’t lie
Two ways of thinking about asynchrony 
From the method signature (how people call it) 
• Foo(); 
• Perform something here ...
Async methods: Your caller ’s assumptions 
“This method’s name ends with ‘Async’, so…” 
“…calling it won’t spawn new threa...
Libraries generally 
shouldn’t use Task.Run()
Your callers should be the ones to call Task.Run 
“await task;” 
Captures the current SyncContext before awaiting. 
When i...
Sync methods: Your caller ’s assumptions 
“There’s a synchronous version of this method…” 
“…I guess it must be faster tha...
Library methods shouldn't lie 
Principles 
In a server app, spinning up threads hurts scalabilty. 
The app (not the librar...
Use 
ConfigureAwait(false)
SynchronizationContext 
Represents a target for work via its Post method 
WindowsFormsSynchronizationContext 
.Post() does...
SynchronizationContext and Await 
Principles 
In a server app, spinning up threads hurts scalabilty. 
The app (not the lib...
SynchronizationContext: ConfigureAwait 
Task.ConfigureAwait(bool continueOnCapturedContext) 
await t.ConfigureAwait(true) ...
Use ConfigureAwait(false) 
Principles 
SynchronizationContext is captured before an await, and used to resume from await. ...
Await all the way
Library perf considerations 
Principles 
The compiler provides, through the await keyword, sequential execution of the cod...
Task.Run is the way to 
create new tasks
Task.Run 
Principles 
Task.Run returns hot tasks (running or completed) created with settings suited to async-await. 
Guid...
Use the 
CancellationToken
Use the CancellationToken 
Principles 
The CancellationToken structure is the way to signal and handle cancellation. 
Guid...
Library perf 
considerations
Library perf considerations 
Principles 
Async methods are faster than what you could write manually, but still slower tha...
Questões?
Resources 
• Talk: Async best practices 
– http://blogs.msdn.com/b/lucian/archive/2013/11/23/talk-mvp-summit-async-best-pr...
Questões?
Patrocinadores “GOLD” 
Twitter: @PTMicrosoft 
http://www.microsoft.com/portugal 
Twitter: @FindMoreC 
http://www.findmore....
Patrocinadores “Silver”
Patrocinadores “Bronze”
http://bit.ly/netponto-aval-50 
* Para quem não puder preencher durante a reunião, 
iremos enviar um email com o link à ta...
Próximas reuniões presenciais 
22/11/2014 – Novembro – 50ª Reunião! (Lisboa) 
13/12/2014 – Dezembro (Lisboa) 
24/01/2015 –...
Upcoming SlideShare
Loading in …5
×

Async-await best practices in 10 minutes

4,235 views

Published on

async-await best practices in 10 minutes

  • Real Money Streams ~ Create multiple streams of wealth from your home! ◆◆◆ https://tinyurl.com/y4urott2
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • I went from getting $3 surveys to $500 surveys every day!! learn more... ★★★ http://ishbv.com/surveys6/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • I made $2,600 with this. I already have 7 days with this...  http://ishbv.com/surveys6/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Async-await best practices in 10 minutes

  1. 1. http://netponto.org 50ª Reunião Presencial @ LISBOA DateTime.Parse(“22-11-2014", new CultureInfo("pt-PT")); hashtag #netponto
  2. 2. 50ª Reunião Lisboa – 22-11-2014 http://netponto.org Async-Await Best Practinces in 10 minutes Paulo Morgado
  3. 3. Paulo Morgado • http://PauloMorgado.NET/ • @PauloMorgado • http://about.me/PauloMorgado • http://www.slideshare.net/PauloJorgeMorgado • http://pontonetpt.org/blogs/paulomorgado/ • http://blogs.msmvps.com/paulomorgado/ • http://weblogs.asp.net/paulomorgado • http://www.revista-programar.info/author/pmorgado/
  4. 4. For goodness’ sake, stop using async void!
  5. 5. Async void is only for event handlers Principles Async void is a “fire-and-forget” mechanism... The caller is unable to know when an async void has finished The caller is unable to catch exceptions thrown from an async void (instead they get posted to the UI message-loop) Guidance Use async void methods only for top-level event handlers (and their like) Use async Task-returning methods everywhere else If you need fire-and-forget elsewhere, indicate it explicitly e.g. “FredAsync().FireAndForget()” When you see an async lambda, verify it
  6. 6. The problem is events. They’re not going away.
  7. 7. Async over events • Principles Callback-based programming, as with events, is hard • Guidance If the event-handlers are largely independent, then leave them as events But if they look like a state-machine, then await is sometimes easier To turn events into awaitable Tasks, use TaskCompletionSource
  8. 8. Is it CPU-bound, or I/O-bound?
  9. 9. Threadpool Principles CPU-bound work means things like: LINQ-over-objects, or big iterations, or computational inner loops. Parallel.ForEach and Task.Run are a good way to put CPU-bound work onto the thread pool. Thread pool will gradually feel out how many threads are needed to make best progress. Use of threads will never increase throughput on a machine that’s under load. Guidance For IO-bound “work”, use await rather than background threads. For CPU-bound work, consider using background threads via Parallel.ForEach or Task.Run, unless you're writing a library, or scalable server-side code.
  10. 10. Don’t lie
  11. 11. Two ways of thinking about asynchrony From the method signature (how people call it) • Foo(); • Perform something here and now. • I’ll regain control to execute something else when it’s done. • var task = FooAsync(); • Initiate something here and now. • I’ll regain control to execute something else “immediately”. From the method implementation (what resources it uses) Uses a CPU core solidly while it runs void Foo() { for (int i=0; i<100; i++) Math.Sin(i); } Hardly touches the CPU async Task FooAsync() { await client.DownloadAsync(); }
  12. 12. Async methods: Your caller ’s assumptions “This method’s name ends with ‘Async’, so…” “…calling it won’t spawn new threads in my server app” “…I can parallelize by simply calling it multiple times” Is this true for your async methods?
  13. 13. Libraries generally shouldn’t use Task.Run()
  14. 14. Your callers should be the ones to call Task.Run “await task;” Captures the current SyncContext before awaiting. When it resumes, uses SyncContext.Post() to resume “in the same place” (If SyncContext is null, uses the TaskScheduler) For application-level code: This behavior is almost always what you want. For library-level code: This behavior is rarely what you want!
  15. 15. Sync methods: Your caller ’s assumptions “There’s a synchronous version of this method…” “…I guess it must be faster than the async version” “…I can call it from the UI thread if the latency’s fine” void Foo() { FooAsync().Wait(); } -- will deadlock!!!
  16. 16. Library methods shouldn't lie Principles In a server app, spinning up threads hurts scalabilty. The app (not the library) is in the best position to manage its own threads. Users will assume they know your method's implementation by looking at its signature. Guidance Define an async signature “FooAsync” when your implementation is truly async. Define a sync signature "Foo" when your implementation is fast and won't deadlock. Don't use blocking calls to Wait() .Result in libraries; that invites deadlocks.
  17. 17. Use ConfigureAwait(false)
  18. 18. SynchronizationContext Represents a target for work via its Post method WindowsFormsSynchronizationContext .Post() does Control.BeginInvoke DispatcherSynchronizationContext .Post() does Dispatcher.BeginInvoke AspNetSynchronizationContext .Post() ensures one-at-a-time … // ~10 in .NET Framework, and you can write your own … // Is the core way for “await” to know how to put you back
  19. 19. SynchronizationContext and Await Principles In a server app, spinning up threads hurts scalabilty. The app (not the library) is in the best position to manage its own threads. Users will assume they know your method's implementation by looking at its signature. Guidance Define an async signature “FooAsync” when your implementation is truly async. Define a sync signature "Foo" when your implementation is fast and won't deadlock. Don't use blocking calls to Wait() .Result in libraries; that invites deadlocks.
  20. 20. SynchronizationContext: ConfigureAwait Task.ConfigureAwait(bool continueOnCapturedContext) await t.ConfigureAwait(true) // default Post continuation back to the current context/scheduler await t.ConfigureAwait(false) If possible, continue executing where awaited task completes Implications Performance (avoids unnecessary thread marshaling) Deadlock (code shouldn’t block UI thread, but avoids deadlocks if it does)
  21. 21. Use ConfigureAwait(false) Principles SynchronizationContext is captured before an await, and used to resume from await. In a library, this is an unnecessary perf hit. It can also lead to deadlocks if the user (incorrectly) calls Wait() on your returned Task.. Guidance In library methods, use "await t.ConfigureAwait(false);"
  22. 22. Await all the way
  23. 23. Library perf considerations Principles The compiler provides, through the await keyword, sequential execution of the code. Guidance Don’t mix async-await with ContinuesWith.
  24. 24. Task.Run is the way to create new tasks
  25. 25. Task.Run Principles Task.Run returns hot tasks (running or completed) created with settings suited to async-await. Guidance Don’t use Task.Factory.StartNew or the Task (or Task<T>) constructor.
  26. 26. Use the CancellationToken
  27. 27. Use the CancellationToken Principles The CancellationToken structure is the way to signal and handle cancellation. Guidance If you want your API to be cancellable, use cancellation tokens. If your code uses APIs that use cancellation tokens, use them. Always check the cancellation tokens.
  28. 28. Library perf considerations
  29. 29. Library perf considerations Principles Async methods are faster than what you could write manually, but still slower than synchronous. The chief cost is in memory allocation (actually, in garbage collection). The "fast path" bypasses some allocations. Guidance Avoid designing "chatty" APIs where async methods are called in an inner loop; make them "chunky". If necessary, cache the returned Task object (even with cache size "1"), for zero allocations per call. As always, don't prematurely optimize!
  30. 30. Questões?
  31. 31. Resources • Talk: Async best practices – http://blogs.msdn.com/b/lucian/archive/2013/11/23/talk-mvp-summit-async-best-practices.aspx • Six Essential Tips For Async – Introduction – http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Three-Essential-Tips-For-Async- Introduction • Curah! async-await General – http://curah.microsoft.com/45553/asyncawait-general • Curah! async-await and ASP.NET – http://curah.microsoft.com/44400/async-and-aspnet
  32. 32. Questões?
  33. 33. Patrocinadores “GOLD” Twitter: @PTMicrosoft http://www.microsoft.com/portugal Twitter: @FindMoreC http://www.findmore.eu
  34. 34. Patrocinadores “Silver”
  35. 35. Patrocinadores “Bronze”
  36. 36. http://bit.ly/netponto-aval-50 * Para quem não puder preencher durante a reunião, iremos enviar um email com o link à tarde
  37. 37. Próximas reuniões presenciais 22/11/2014 – Novembro – 50ª Reunião! (Lisboa) 13/12/2014 – Dezembro (Lisboa) 24/01/2015 – Janeiro (Lisboa) ??/??/2015 – ????? (Porto) ??/??/2015 – ????? (?????) Reserva estes dias na agenda! :)

×