public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()

Slides:



Advertisements
Similar presentations
TechReady 16 4/1/2017 Async Clinic
Advertisements

 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
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.
7. Nested “try” blocks 3. Awaiter Pattern struct FooAsync_StateMachine : IAsyncStateMachine { //(1,2,3) private int _state; public AsyncTaskMethodBuilder.
C++ await Deon Brewis std::future additions:
IAP C# Lecture 3 Parallel Computing Geza Kovacs. Sequential Execution So far, all our code has been executing instructions one after another, on a single.
Lecture 16 Subroutine Calls and Parameter Passing Semantics Dragon: Sec. 7.5 Fischer: Sec Procedure declaration procedure p( a, b : integer, f :
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
Understand Error Handling Software Development Fundamentals LESSON 1.4.
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!.
{ async patterns } - or - using the asynchronous library in the.Net 4.5 Framework for more than keeping your UI responsive.
please wait for the next slide clicking won’t make it come any faster.
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
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.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
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.
Modern Concurrency Abstractions for C# by Nick Benton, Luca Cardelli & C´EDRIC FOURNET Microsoft Research.
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
Joe Hummel, PhD Technical Staff: Pluralsight Adjunct Professor: UIC, LUC
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();
A Revolutionary Programming Pattern that Will Clean up your Code : Coroutines in C++ David Sackstein ACCU 2015.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Parallel Programming: Responsiveness vs. Performance Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois,
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois, Chicago stuff:
Future of VB and C# Lucian Wischik VB Language PM Microsoft.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
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();

PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Java Thread and Memory Model
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
TAP into async programming
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.
Wel come To Seminar On C#.
Methods.
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.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Async Made Simple in Windows 8, with C# and Visual Basic Alex Turner Program Manager VB/C# Compilers Microsoft Corporation DEV332.
Lambda Functions & Closures A Sydney PHP Group Presentation 2 nd October 2008 By Timothy Chandler.
Asynchronous Programming Writing Concurrent Code in C# SoftUni Team Technical Trainers Software University
THE FUTURE OF C#: GOOD THINGS COME TO THOSE WHO ‘AWAIT’ Joseph Albahari SESSION CODE: DEV411 (c) 2011 Microsoft. All rights reserved.
Linux Kernel Development - Robert Love
5/16/2018 © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks.
Singleton Pattern Command Pattern
New Features of C# Kuppurasu Nagaraj Microsoft Connect 2016
Staying Afloat in the .NET Async Ocean
12 Asynchronous Programming
Asynchronous Programming in .NET
TechEd /9/ :20 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered.
when it needs to be done at compile-time
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.
03 | Async Programming & Networking Intro
.NET Core Summer event 2019 – Brno, CZ
Chengyu Sun California State University, Los Angeles
Presentation transcript:

public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(() => PausePrint()); } public static Task PausePrintAsync() { var tcs = new TaskCompletionSource (); new Timer(_ => { Console.WriteLine("Hello"); tcs.SetResult(true); }).Change(10000, Timeout.Infinite); return tcs.Task; } public static async Task PausePrintAsync() { await Task.Delay(10000); Console.WriteLine("Hello"); } Synchronous Asynchronous public static void PausePrint() { var end = DateTime.Now + TimeSpan.FromSeconds(10); while(DateTime.Now < end); Console.WriteLine("Hello"); } public static void PausePrint() { Task t = PausePrintAsync(); t.Wait(); } “async over sync” “sync over async”

TaskAsync await

' In VB, the expression itself determines void- or Task-returning (not the context). Dim void_returning = Async Sub() Await LoadAsync() : m_Result = "done" End Sub Dim task_returning = Async Function() Await LoadAsync() : m_Result = "done" End Function ' If both overloads are offered, you must give it Task-returning. Await Task.Run(Async Function()... End Function) // In C#, the context determines whether async lambda is void- or Task-returning. Action a1 = async () => { await LoadAsync(); m_Result="done"; }; Func a2 = async () => { await LoadAsync(); m_Result="done"; }; // Q. Which one will it pick? await Task.Run( async () => { await LoadAsync(); m_Result="done"; }); // A. If both overloads are offered, it will pick Task-returning. Good! class Task { static public Task Run(Action a) {...} static public Task Run(Func a) {...}... }

// ORIGINAL CODE async Task FooAsync() { BODY } // APPROXIMATELY WHAT THE COMPILER GENERATES... Task FooAsync() { var sm = new FooAsyncStruct(); sm.tcs = new TaskCompletionSource(); sm.MoveNext(); return sm.tcs.Task; } struct FooAsyncStruct { public TaskCompletionSource tcs; private void MoveNext() { try { TRANSFORMED_BODY } catch (Exception ex) { tcs.SetException(ex); return; } tcs.SetResult(); }

// ORIGINAL CODE var r = await t; // APPROXIMATELY WHAT THE COMPILER GENERATES... var tmp = t.GetAwaiter(); if (!tmp.IsCompleted) { var ec = ExecutionContext.Capture() ((INotifyCompletion)tmp).OnCompleted(_ => ExecutionContext.Run(ec, K1)); return; } K1: var r = tmp.GetResult(); // The two lines in italics are executed from within a routine inside mscorlib // The argument "K1" represents a delegate that, when executed, resumes execution at the label. // If "tmp" is a struct, any mutations after IsCompleted before GetResult may be lost. // If tmp implements ICriticalNotifyCompletion, then it calls tmp.UnsafeOnCompleted instead. // The variable "ec" gets disposed at the right time inside the lambda // If ec is null, then it invokes K1 directly instead of via ExecutionContext.Run // There are optimizations for the case where ExecutionContext is unmodified.

// Usage: await storyboard1.PlayAsync(); public static async Task PlayAsync(this Storyboard storyboard) { var tcs = new TaskCompletionSource (); EventHandler lambda = (s,e) => tcs.TrySetResult(null); try { storyboard.Completed += lambda; storyboard.Begin(); await tcs.Task; } finally { storyboard.Completed -= lambda; } ' Usage: Await storyboard1.PlayAsync() Async Function PlayAsync(sb As Animation.Storyboard) As Task Dim tcs As New TaskCompletionSource(Of Object) Dim lambda As EventHandler(Of Object) = Sub() tcs.TrySetResult(Nothing) Try AddHandler sb.Completed, lambda sb.Begin() Await tcs.Task Finally RemoveHandler sb.Completed, lambda End Try End Function

// Usage: await button1.WhenClicked(); public static async Task WhenClicked(this Button button) { var tcs = new TaskCompletionSource (); RoutedEventHandler lambda = (s,e) => tcs.TrySetResult(null); try { button.Click += lambda; await tcs.Task; } finally { button.Click -= lambda; }

sync async multiplesingle TIEnumerable Task IObservable

Library methods shouldn’t lie. Be honest. Use “XxAsync” if, and only if, you’re not thread-bound (with a few notable exceptions). Suffix should help caller to understand implementation.

Library methods shouldn’t lie. Be honest. Use “XxAsync” if, and only if, you’re not thread-bound (with a few notable exceptions). Suffix should help caller to understand implementation. Library methods might be called from various environments. Context becomes critical. Be agnostic whenever possible. ConfigureAwait(continueOnCapturedContext:false) is your best friend.

Library methods shouldn’t lie. Be honest. Use “XxAsync” if, and only if, you’re not thread-bound (with a few notable exceptions). Suffix should help caller to understand implementation. Library methods might be called from various environments. Context becomes critical. Be agnostic whenever possible. ConfigureAwait(continueOnCapturedContext:false) is your best friend. Library methods might be used from perf-sensitive code. Performance becomes critical. Design for chunky instead of chatty. Optimize the synchronously completing cases.

async void button1_Click(…) { Action work = CPUWork; await ScheduleAsync(work); … } async Task ScheduleAsync(Action work) { work(); } async void button1_Click(…) { Action work = CPUWork; await Task.Run(() => work()); … }

…; Task.Delay(1000); …; …; await Task.Delay(1000); …; Parallel.For(0, 10, async i => { await Task.Delay(1000); }); await Task.Factory.StartNew( async () => { await Task.Delay(1000); }); await Task.Run( async () => { await Task.Delay(1000); });

var tcs = new TaskCompletionSource (); Task.Run(delegate { T result = Foo(); tcs.SetResult(result); }); return tcs.Task; var tcs = new TaskCompletionSource (); Task.Run(delegate { try { T result = Foo(); tcs.SetResult(result); } catch(Exception e) { tcs.SetException(e); } }); return tcs.Task; void button1_Click(…) { FooAsync().Wait(); } async Task FooAsync() { await Task.Delay(1000); } 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); }

Async/Await FAQ: faq.aspx Task-based Async Pattern: “Async over Sync” & “Sync over Async”: Forking: methods.aspx Common problems: debugging-of-async-methods.aspx Performance: Await Anything storyboard-and-other-things.aspx button-click.aspx WinRT & Async deep-with-winrt-and-await.aspx net-tasks-as-winrt-asynchronous-operations.aspx Parallel Patterns