TechReady 16 4/1/2017 Async Clinic

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

1 Polyphonic C# Nick Benton Luca Cardelli Cédric Fournet Microsoft Research.
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
static void Main() { int i = 0; if (i == 0) { int a = 5; int b = 15; if (a == 5) { int c = 3; int d = 99; }
James Kolpack, InRAD LLC popcyclical.com. CodeStock is proudly partnered with: Send instant feedback on this session via Twitter: Send a direct message.
DEV324 C# VB 7.0 Managed Code C# VB 8.0 Generics C# VB 9.0 Language Integrated Query C# VB 10.0 Dynamic + Language Parity.
Parallel Extensions to the.NET Framework Daniel Moth Microsoft
7. Nested “try” blocks 3. Awaiter Pattern struct FooAsync_StateMachine : IAsyncStateMachine { //(1,2,3) private int _state; public AsyncTaskMethodBuilder.
FUTURE OF.NET PARALLEL PROGRAMMING Joseph Albahari SESSION CODE: DEV308 (c) 2011 Microsoft. All rights reserved.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Pavel Yosifovich Hi-Tech College
Asynchronous programming Deadlock All The Things!.
{ async patterns } - or - using the asynchronous library in the.Net 4.5 Framework for more than keeping your UI responsive.
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.
Async Programming WITH ASYNC TASK
02/05/2008CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying an earlier.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
Threads in C# Threads in C#.
1 Thread Pools Representation and Management of Data on the Internet.
02/01/2007CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook.
ThreadThread Thread Basics Thread Synchronization Animations.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
Async void is only for top-level event handlers. Use TaskCompletionSource to wrap Tasks around events. Use the threadpool for CPU-bound code, but not.
Async void is only for top-level event handlers. Use the threadpool for CPU-bound code, but not IO-bound. Use TaskCompletionSource to wrap Tasks around.
Managed Code Generics Language Integrated Query Dynamic + Language Parity C# VB 11.0 Windows Runtime + Asynchrony C# VB 7.0 C# VB.
Neal Stublen Practice Solution  Create a new solution  Add a WinForms project  Add a Class Library project  Reference the library.
DEV301. // Synchronous TResult Foo(...); // Asynchronous Programming Model (APM) IAsyncResult BeginFoo(..., AsyncCallback callback, object state);
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
please wait for the next slide clicking won’t make it come any faster.
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.

Huseyin YILDIZ Software Design Engineer Microsoft Corporation SESSION CODE: DEV314.
IAsyncResult ar = BeginSomething(…); // Do other work, checking ar.IsCompleted int result = EndSomething(ar);
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
Module 8 Enhancing User Interface Responsiveness.
TAP into async programming
Other news? async and await Anonymous types (var, dynamic) Tuples Object instantiation Extension methods UCN Teknologi/act2learn1FEN 2014.
please wait for the next slide clicking won’t make it come any faster.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET library developers : with knowledge of async/await in C# / VB interested in low-level.
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET developers: familiar with parallel programming support in Visual Studio 2010 and.NET.
C# Present and Future Marita Paletsou Software Engineer.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
THE FUTURE OF C#: GOOD THINGS COME TO THOSE WHO ‘AWAIT’ Joseph Albahari SESSION CODE: DEV411 (c) 2011 Microsoft. All rights reserved.
Threading Lecture 11 M. Ipalakova.
Multi Threading.
Advanced C++ Programming
Multithreading Chapter 9.
Threads II IS
Staying Afloat in the .NET Async Ocean
12 Asynchronous Programming
12/2/2018 4:10 AM © 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered.
TechEd /9/2018 4:17 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
JavaScript Reserved Words
Threads, Handlers, and AsyncTasks
03 | Async Programming & Networking Intro
Presentation transcript:

TechReady 16 4/1/2017 Async Clinic Lucian Wischik, Mads Torgersen, Stephen Toub (MSFT) Stephen Cleary (MVP) © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Brainteasers

Symptom: Not Running Asynchronously async void button1_Click(…) { … await Task.Run(() => work()); … } async void button1_Click(…) { … await ScheduleAsync(work); … } async Task ScheduleAsync(Action work) { work(); } Problem: Thinking ‘async’ forks. Solution: Use Task.Run around a synchronous method if you need to offload… but don’t expose public APIs like this.

Symptom: Completing Too Quickly …; await Task.Delay(1000); …; …; Task.Delay(1000); …; Problem: Neglecting to await. Solution: Await your awaitables. Problem: Async void lambda. Solution: Use extreme caution (& knowledge) when passing around async lambdas as void-returning delegates. Parallel.For(0, 10, async i => { await Task.Delay(1000); }); Problem: Task<Task> instead of Task. Solution: Make sure you’re unwrapping your Tasks, explicitly (Unwrap) or implicitly. await Task.Run( async () => { await Task.Delay(1000); }); await Task.Factory.StartNew( async () => { await Task.Delay(1000); });

Symptom: Method Not Completing async void button1_Click(…) { await FooAsync(); } async Task FooAsync() { await Task.Delay(1000); } async void button1_Click(…) { await FooAsync(); } async Task FooAsync() { await Task.Delay(1000).ConfigureAwait(false); } void button1_Click(…) { FooAsync().Wait(); } async Task FooAsync() { await Task.Delay(1000); } Problem: Deadlocking UI thread. Solution: Don’t synchronously wait on the UI thread. Problem: Deadlocking UI thread. Solution: Use ConfigureAwait(false) whenever possible. var tcs = new TaskCompletionSource<T>(); Task.Run(delegate { try { T result = Foo(); tcs.SetResult(result); } catch(Exception e) { tcs.SetException(e); } }); return tcs.Task; var tcs = new TaskCompletionSource<T>(); Task.Run(delegate { T result = Foo(); tcs.SetResult(result); }); return tcs.Task; Problem: Awaited task never completes. Solution: Always complete Tasks when the underlying operation has ended. Always.

Special Topics

TechReady 16 4/1/2017 Throttling (1) async Task LotsOfWorkAsync() { var throttle = Throttle<string>(async message => { await Task.Yield(); Console.WriteLine(message);}, maxParallelism: Environment.ProcessorCount); throttle.Post("lots"); throttle.Post("of"); throttle.Post("work"); throttle.Complete(); // Signal that we're done enqueuing work. await throttle.Completion; } static ITargetBlock<T> Throttle<T>(Func<T, Task> worker, int max) { var opts = new ExecutionDataflowBlockOptions() {MaxDegreeOfParallelism = max}; return new ActionBlock<T>(worker, opts); © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

TechReady 16 4/1/2017 Throttling (2) public async Task<List<House>> LoadHousesAsync(int first, int last) { var loadedHouses = new List<House>(); var queue = new Queue<int>(Enumerable.Range(first, last – first + 1)); // Throttle the rate of issuing requests... var worker1 = WorkerAsync(queue, loadedHouses); var worker2 = WorkerAsync(queue, loadedHouses); var worker3 = WorkerAsync(queue, loadedHouses); await Task.WhenAll(worker1, worker2, worker3); return loadedHouses; } * What would we do if there weren’t 5 houses but 500? * Can’t make 500 requests all at once. We need to throttle the rate of requests. * Here’s what I think is the easiest idiom. * A queue of work-items. * Async method WorkerAsync runs through the queue and fires requests, one after the other. * And if I kick off three of these workers, then I’ll have throttled it to 3 at a time! private async Task WorkerAsync(Queue<int> queue, List<House> results) { while (queue.Count > 0) int i = queue.Dequeue(); var house = await House.LoadFromDatabaseAsync(i); results.Add(house); } © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Throttling (3) Explicitly Controlled SemaphoreSlim await Task.WhenAll(from i in Enumerable.Range(0, N) select Task.Run(async delegate { … })); SemaphoreSlim var sem = new SemaphoreSlim(N); await sem.WaitAsync(); …; sem.Release(); ConcurrentExclusiveSchedulerPair var f = new TaskFactory( new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, N).ConcurrentScheduler); f.StartNew(…); // note: only counts tasks currently on a thread ActionBlock var ab = new ActionBlock<T>(async t => …, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = N });

Task-based Async Pattern (TAP) “Async” suffix Signature Task<TResult> XxAsync( T1 Arg1, T2 Arg2, CancellationToken cancellationToken, IProgress<TProgress> progress); Parameters matching synchronous method (no ref or out) Cancellation/progress parameters only if supported Returns Task or Task<TResult> Behavior Returns quickly to caller Returned Task must be “hot” May complete synchronously Exceptions stored in returned Task (only usage exceptions allowed to escape synchronously)

async & await are about joins, not forks public static Task PausePrintAsync() { // Requires a thread for all // of its processing return Task.Run(() => { Thread.Sleep(10000); Console.WriteLine("Hello"); }); } public static Task PausePrintAsync() { // Don’t consume threads // when no threads are needed var t = Task.Delay(10000); return t.ContinueWith(_ => { Console.WriteLine("Hello")); }); } Task Synchronous join Asynchronous join task.Wait(); await task;