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.

Slides:



Advertisements
Similar presentations
Mike Barnett RSDE Microsoft Research Nikolai Tillmann RSDE Microsoft Research TL51.
Advertisements

TechReady 16 4/1/2017 Async Clinic
James Kolpack, InRAD LLC popcyclical.com. CodeStock is proudly partnered with: Send instant feedback on this session via Twitter: Send a direct message.
Chapter 1 IDE and Tools for Developing CLR-based Programs Yingcai Xiao.
7. Nested “try” blocks 3. Awaiter Pattern struct FooAsync_StateMachine : IAsyncStateMachine { //(1,2,3) private int _state; public AsyncTaskMethodBuilder.
Pavel Yosifovich Hi-Tech College
Cole Durdan.  What is asynchronous programming?  Previous patterns  Task Based Async Programming .NET 4.5 Keywords  What happens in an async. method?
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Adjunct Professor: U. of Illinois, Chicago and Loyola University Chicago
Asynchronous programming Deadlock All The Things!.
Stephen Toub Parallel Computing Platform Microsoft Corporation.
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
Performance evaluation of plagiarism detection method based on the intermediate language Vedran Juričić Tereza Jurić Marija Tkalec.
Antonio Cisternino & Diego Colombo VisualStorms Tools Another Brick in the Robot... Università degli Studi di Pisa.
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.
WHO WILL BENEFIT FROM THIS TALK TOPICS WHAT YOU’LL LEAVE WITH Web app developers who are already familiar with Windows Azure with scaling needs. Asynchronous.
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.
Introduction to.NET Frank McCown COMP GUI Programming Harding University.
 George Chrysanthakopoulos Software Architect Microsoft Corporation.
App Windows UI object Windows object App code Windows object.
DEV490 .NET Framework: CLR – Under The Hood
Joe Hummel, PhD Technical Staff: Pluralsight Adjunct Professor: UIC, LUC
Financial Information Management Stefano Grazioli.
DEV301. // Synchronous TResult Foo(...); // Asynchronous Programming Model (APM) IAsyncResult BeginFoo(..., AsyncCallback callback, object state);
Introduction to.NET Frank McCown TechLunch Old Dominion University March 28, 2007.
please wait for the next slide clicking won’t make it come any faster.
Using and Building an Automatic Program Verifier K. Rustan M. Leino Research in Software Engineering (RiSE) Microsoft Research, Redmond Lecture 3 Marktoberdorf.
Parallel Programming: Responsiveness vs. Performance Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois,
public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois, Chicago stuff:
1 Web Based Programming Section 8 James King 12 August 2003.
Future of VB and C# Lucian Wischik VB Language PM Microsoft.
WHO WILL BENEFIT FROM THIS TALK TOPICS WHAT YOU’LL LEAVE WITH ASP.NET developers, including Web Forms & MVC History of async programming in.NET How async.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();

IAsyncResult ar = BeginSomething(…); // Do other work, checking ar.IsCompleted int result = EndSomething(ar);
MSIL C#.NET Software Development. MSIL AKA CIL What all.NET languages compile to What all.NET languages compile to Binary Intermediate Language Binary.
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
Parallel Pattern Library Resource Manager Task Scheduler Task Parallel Library Task Parallel Library Parallel LINQ Managed Native Key: Threads Operating.
TAP into async programming
The Execution System1. 2 Introduction Managed code and managed data qualify code or data that executes in cooperation with the execution engine The execution.
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
Overview CNS 3260 C#.NET Software Development. 2.NET Framework Began in 2000 Developed in three years (2000 to 2003) Operating System Hardware.NET Framework.
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# 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.
Introduction to JENNIFER | Aug, C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A.
Joe Hummel, the compiler is at your service Chicago Coder Conference, June 2016.
Async Made Simple in Windows 8, with C# and Visual Basic Alex Turner Program Manager VB/C# Compilers Microsoft Corporation DEV332.
Asynchronous Programming Writing Concurrent Code in C# SoftUni Team Technical Trainers Software University
Asynchronous Programming with C# v.Next
The Future of C# and Visual Basic
5/16/2018 © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks.
5/19/2018 1:01 AM © Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN.
TechEd /6/2018 6:15 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Frank McCown TechLunch Old Dominion University March 28, 2007
Async or Parallel? No they aren’t the same thing!
CS360 Windows Programming
Chapter 1 IDE and Tools for Developing CLR-based Programs
Threads Chate Patanothai.
12 Asynchronous Programming
Asynchronous Programming in .NET
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/ :20 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered.
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Async #2 Lucian Wischik Senior Program Manager Microsoft NDC 2012.
Frank McCown TechLunch Old Dominion University March 28, 2007
03 | Async Programming & Networking Intro
CMSC 202 Threads.
.NET Core Summer event 2019 – Brno, CZ
Presentation transcript:

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 perf that understand this is based on the Developer Preview Getting the Right Mental Model Knowing When Not To Use Async Avoiding Allocations Caring About Context Minimizing Suspensions Knowledge of: when to care about optimizing your async implementations …and how to do it

public static void SimpleBody() { Console.WriteLine("Hello, Async World!"); } 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 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 }

public static async Task SimpleBody() { Console.WriteLine("Hello, Async World!"); } public static async Task SimpleBody() { Console.WriteLine("Hello, Async World!"); }.method public hidebysig static class [mscorlib]System.Threading.Tasks.Task SimpleBody() cil managed {.custom instance void [mscorlib]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() = ( ) // Code size 32 (0x20).maxstack 2.locals init ([0] valuetype Program/' d__0' V_0) IL_0000: ldloca.s V_0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_000c: ldloca.s V_0 IL_000e: call instance void Program/' d__0'::MoveNext() IL_0013: ldloca.s V_0 IL_0015: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_001a: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() IL_001f: ret }.method public hidebysig static class [mscorlib]System.Threading.Tasks.Task SimpleBody() cil managed {.custom instance void [mscorlib]System.Diagnostics.DebuggerStepThroughAttribute::.ctor() = ( ) // Code size 32 (0x20).maxstack 2.locals init ([0] valuetype Program/' d__0' V_0) IL_0000: ldloca.s V_0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_000c: ldloca.s V_0 IL_000e: call instance void Program/' d__0'::MoveNext() IL_0013: ldloca.s V_0 IL_0015: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_001a: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() IL_001f: 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/' d__0'::'<>1__state' IL_0008: ldc.i4.m1 IL_0009: bne.un.s IL_000d 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 } catch [mscorlib]System.Exception { IL_0019: stloc.1 IL_001a: ldarg.0 IL_001b: ldc.i4.m1 IL_001c: stfld int32 Program/' d__0'::'<>1__state' IL_0021: ldarg.0 IL_0022: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_0027: ldloc.1 IL_0028: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException( class [mscorlib]System.Exception) IL_002d: leave.s IL_0041 } IL_002f: ldarg.0 IL_0030: ldc.i4.m1 IL_0031: stfld int32 Program/' d__0'::'<>1__state' IL_0036: ldarg.0 IL_0037: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_003c: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetResult() IL_0041: 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/' d__0'::'<>1__state' IL_0008: ldc.i4.m1 IL_0009: bne.un.s IL_000d 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 } catch [mscorlib]System.Exception { IL_0019: stloc.1 IL_001a: ldarg.0 IL_001b: ldc.i4.m1 IL_001c: stfld int32 Program/' d__0'::'<>1__state' IL_0021: ldarg.0 IL_0022: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_0027: ldloc.1 IL_0028: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException( class [mscorlib]System.Exception) IL_002d: leave.s IL_0041 } IL_002f: ldarg.0 IL_0030: ldc.i4.m1 IL_0031: stfld int32 Program/' d__0'::'<>1__state' IL_0036: ldarg.0 IL_0037: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/' d__0'::'<>t__builder' IL_003c: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetResult() IL_0041: ret }

[CompilerGenerated] private class d__0 { private int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public Action <>t__MoveNextDelegate; public void MoveNext(); } [CompilerGenerated] private class 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; } 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(); var $awaiter = FooAsync().GetAwaiter(); if (!$awaiter.IsCompleted) { SAVE_STATE; $awaiter.OnCompleted(CompletionDelegate); return; Label: RESTORE_STATE; } TResult result = $awaiter.GetResult();

public async Task FooAsync() {... // doesn’t yield return true; } public async Task FooAsync() {... // doesn’t yield return true; } public async Task FooAsync() {... // doesn’t yield return; } public async Task FooAsync() {... // doesn’t yield return; } public async Task FooAsync() {... // doesn’t yield return null; } public async Task FooAsync() {... // doesn’t yield return null; }

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); } } 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); } } public override async Task ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); } public override async Task ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); }

private Task m_lastTask; public override Task ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { var tcs = new TaskCompletionSource (); 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 (); tcs.SetException(e); return tcs.Task; } private Task m_lastTask; public override Task ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { var tcs = new TaskCompletionSource (); 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 (); tcs.SetException(e); return tcs.Task; }

async void button1_Click(…) { await DoWorkAsync(); } async void button1_Click(…) { await DoWorkAsync(); } async void button1_Click(…) { DoWorkAsync().Wait(); } async void button1_Click(…) { DoWorkAsync().Wait(); } async Task DoWorkAsync() { await Task.Run(…); Console.WriteLine("Done task"); } async Task DoWorkAsync() { await Task.Run(…); Console.WriteLine("Done task"); } 1. DoWorkAsync invoked on UI thread 3. Await captures SynchronizationContext and hooks up a continuation to run when task completes 4. UI blocks waiting for DoWorkAsync-returned Task to complete 6. UI thread still blocked waiting for async operation to complete. Deadlock! 6. UI thread still blocked waiting for async operation to complete. Deadlock!.ConfigureAwait(false) avoids deadlock. async Task DoWorkAsync() { await Task.Run(…).ConfigureAwait(false); Console.WriteLine("Done task"); } async Task DoWorkAsync() { await Task.Run(…).ConfigureAwait(false); Console.WriteLine("Done task"); } 2. Task.Run schedules work to run on thread pool 5. Task.Run task completes on pool & invokes continuation which Posts back to UI thread

public static async Task FooAsync() { var t1 = BarAsync(); var t2 = BazAsync(); await t1; await t2; } public static async Task FooAsync() { var t1 = BarAsync(); var t2 = BazAsync(); await t1; await t2; } public static async Task FooAsync() { var t1 = BarAsync(); var t2 = BazAsync(); await Task.WhenAll(t1, t2); } public static async Task FooAsync() { var t1 = BarAsync(); var t2 = BazAsync(); await Task.WhenAll(t1, t2); }

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. Avoid unnecessary awaits.

RELATED SESSIONSARTICLES, SAMPLES, VIDEOS, BLOGS IDTitleSpeaker 834What's New in.NET Framework 4.5Joshua Goodman 816Future Directions for C# and Visual BasicAnders Hejlsberg 810C# and Visual Basic in Visual Studio vNext: Windows 8 Async Made Simple Mads Torgersen; Alex Turner 804Building IIS and ASP.NET Applications with the Power of Async Damian Edwards 808Building Parallelized Applications with.NET and Visual Studio Stephen Toub 829The Zen of Async: Best Practices for Best Performance Stephen Toub nc