12 Asynchronous Programming

Slides:



Advertisements
Similar presentations
Parallel Extensions to the.NET Framework Daniel Moth Microsoft
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Asynchronous programming Using Task, async and await Asynchronous programming1.
Asynchronous Programming with C# and WinRT
Asynchronous programming Deadlock All The Things!.
Async Programming WITH ASYNC TASK
Threads in C# Threads in C#.
Ceng Operating Systems Chapter 2.1 : Processes Process concept Process scheduling Interprocess communication Deadlocks Threads.
INPUT/OUTPUT ORGANIZATION INTERRUPTS CS147 Summer 2001 Professor: Sin-Min Lee Presented by: Jing Chen.
SE-565 Software System Requirements More UML Diagrams.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Node.js - What is Node.js? -
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Threads and Processes.
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
111 © 2002, Cisco Systems, Inc. All rights reserved.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
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:
1 Chapter 2.1 : Processes Process concept Process concept Process scheduling Process scheduling Interprocess communication Interprocess communication Threads.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
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.
Concurrent Programming and Threads Threads Blocking a User Interface.
Reactive pattern matching for F# Part of “Variations in F#” research project Tomáš Petříček, Charles University in Prague
CS333 Intro to Operating Systems Jonathan Walpole.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
1 Review of Process Mechanisms. 2 Scheduling: Policy and Mechanism Scheduling policy answers the question: Which process/thread, among all those ready.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
Discussion Week 2 TA: Kyle Dewey. Overview Concurrency Process level Thread level MIPS - switch.s Project #1.
Module 8 Enhancing User Interface Responsiveness.
Multi-Threading in Java
TAP into async programming
1 Why Threads are a Bad Idea (for most purposes) based on a presentation by John Ousterhout Sun Microsystems Laboratories Threads!
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
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.
Multithreading / Concurrency
Processes and threads.
Asynchronous Programming with C# v.Next
The Future of C# and Visual Basic
TechEd /6/2018 6:15 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Processes and Threads Processes and their scheduling
Thread Fundamentals Header Advanced .NET Threading, Part 1
CS399 New Beginnings Jonathan Walpole.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Async or Parallel? No they aren’t the same thing!
Staying Afloat in the .NET Async Ocean
Multithreading.
Multithreaded Programming
Process Description and Control
Android Topics Asynchronous Callsbacks
Threaded Programming in Python
EE 472 – Embedded Systems Dr. Shwetak Patel.
Hold up, wait a minute, let me put some async in it
Enable long running Function Orchestrations
Lecture 12: The Fetch Api and AJAx
Building Web Applications with Microsoft ASP
Lecture 12: The Fetch Api and AJAx
03 | Async Programming & Networking Intro
Chapter 3: Process Management
Threads CSE 2431: Introduction to Operating Systems
Asynchronous Programming CS Programming Languages for Web Applications
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

12 Asynchronous Programming .NET and .NET Core 12 Asynchronous Programming Pan Wuming 2017

Topics Asynchronous programming Tasks for an I/O-Bound Operation Tasks for a CPU-Bound Operation The Asynchronous Programming Model async Programming in F#

Asynchronous programming It is a key technique that makes it straightforward to handle: blocking I/O and concurrent operations on multiple cores. It is not HPC or Parallel Programming Typically a task is decomposed into many parts running on different computing node. Parallel programming in the .NET Framework The .NET Framework provides three patterns for performing asynchronous operations. Only Task-based Asynchronous Pattern (TAP) is recommended now.

Task-based async APIs and the language-level asynchronous programming Handles more server requests by yielding threads to handle more requests while waiting for I/O requests to return. Enables UIs to be more responsive by yielding threads to UI interaction while waiting for I/O requests and by transitioning long- running work to other CPU cores. Many of the newer .NET APIs are asynchronous. It's easy to write async code in .NET!

Task and Task<T> Promise Model of Concurrency Task represents a single operation which does not return a value. Task<T> represents a single operation which returns a value of type T . Tasks are abstractions of work happening asynchronously, and not abstractions over threading. The OS is essentially asynchronous through interrupts. The await keyword, provides a higher-level abstraction for using tasks.

Tasks for an I/O-Bound Operation Threads are freed up when the I/O-bound work starts, rather than when it finishes.

public Task<string> GetHtmlAsync() { // Execution is synchronous here var client = new HttpClient(); return client.GetStringAsync("http://www.dotnetfoundation.org"); }

public async Task<string> GetFirstCharactersCountAsync(string url, int count) { var client = new HttpClient(); var page = await client.GetStringAsync("http://www.microsoft.com/net/"); // Execution resumes when the client.GetStringAsync task completes, // becoming synchronous again. if (count > page.Length) return page; else return page.Substring(0, count); }

Tasks for a CPU-Bound Operation They can be used to keep the caller of the async method responsive. This does not provide any protection for shared data.

public async Task<int> CalculateResult(InputData data) { // This queues up the work on the threadpool. var expensiveResultTask = Task.Run(() => DoExpensiveCalculation(data)); // Note that at this point, you can do some other work concurrently, // as CalculateResult() is still executing! // Execution of CalculateResult is yielded here! var result = await expensiveResultTask; return result; }

Key Pieces to Understand Async code can be used for both I/O-bound and CPU-bound code, but differently for each scenario. Async code uses Task<T> and Task , which are constructs used to model work being done in the background. The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

Control Flow

async Modifier Use the async modifier to specify that a method, lambda expression, or anonymous method is asynchronous. If the method that the async keyword modifies doesn't contain an await expression or statement, the method executes synchronously. An async method can have a return type of Task, Task<TResult>, or void. You use the void return type primarily to define event handlers.

The Asynchronous Model For I/O-bound code, you await an operation which returns a Task or Task<T> inside of an async method. For CPU-bound code, you await an operation which is started on a background thread with the Task.Run method.

I/O-Bound Example: Downloading data from a web service Async Lambdas private readonly HttpClient _httpClient = new HttpClient(); downloadButton.Clicked += async (o, e) => { var stringData = await _httpClient.GetStringAsync(URL); DoSomethingWithData(stringData); };

CPU-bound Example: Performing a Calculation for a Game private DamageResult CalculateDamageDone() { // Code omitted: } calculateButton.Clicked += async (o, e) => var damageResult = await Task.Run(() => CalculateDamageDone()); DisplayDamage(damageResult); };

Waiting for Multiple Tasks to Complete Task.WhenAll and Task.WhenAny allow you to write asynchronous code which performs a non-blocking wait on multiple background jobs.

public async Task<User> GetUserAsync(int userId) { // Code omitted: } public static async Task<IEnumerable<User>> GetUsersAsync(IEnumerable<int> userIds) var getUserTasks = new List<Task<User>>(); foreach (int userId in userIds) getUserTasks.Add(GetUserAsync(userId)); return await Task.WhenAll(getUserTasks);

In F# The core of async programming in F# is Async<‘T> , a representation of work that can be triggered to run in the background. let! use! do! return return!

let fetchHtmlAsync url = let uri = Uri(url) use webClient = new WebClient() let! html = webClient.AsyncDownloadString(uri) return html } let html = "http://dotnetfoundation.org" |> fetchHtmlAsync |> Async.RunSynchronously printfn "%s" html

Case Study The chain of asyncs The async event

Most Responsive!