async in .net

9
ASYNC IN .NET

Upload: rtigger

Post on 10-May-2015

945 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Async in .NET

ASYNC IN .NET

Page 2: Async in .NET

What is Async?

Synchronousevery line of code is executed in orderthe next line doesn’t execute until the

current one is completed Asynchronous

an operation is started, and then code continues

A callback is usually executed when the operation completes

Page 3: Async in .NET

Why Async?

Essential when executing long running operations, such as file or network access

Especially important when starting operations on the UI thread – async prevents the UI from locking up while the operation completes

Page 4: Async in .NET

Async Programming Model (APM) .NET’s first crack at async Uses method signatures like Begin* and

End*i.e. Stream.BeginRead

Returns an “IAsyncResult” object to query status of operation

Usually executes a callback when operation is completed

Page 5: Async in .NET

Event-based Async Pattern (EAP) 2nd attempt at Async Uses events to notify when async

operations completei.e. WebClient.OnDownloadStringCompleted

Operation is started with *Asynci.e. WebClient.DownloadStringAsync

No IAsyncResult – hard to query current statusSometimes they have “OnProgress” events

Page 6: Async in .NET

Task Async Pattern

Uses Task Parallel Library to wrap APM methods

Task.Factory.FromAsync(Begin*, End*, args)

Get access to Task functionalityContinueWith to execute code after

operation is completeContinueWhenAll to wait for multiple async

operations

Page 7: Async in .NET

The New Hotness – Async & Await In an effort to simplify async even more,

Async and Await keywords introduced into .net 4.5

Async – indicates that a method has a point at which it can be suspended

Await – suspends the current method until an operation yields a result

Page 8: Async in .NET

Async Control Flow Starts an async operation by calling async

method Execute whatever other code you’d like

while operation executes Call await to suspend method until async

operation returnsThis will return control to the previous method in

the call stack Once async operation returns, control is

restored to method and continues as normal

Page 9: Async in .NET

Things To Know This is all managed through Tasks

Await essentially calls Task.Wait() and automatically returns Task.Result

Most of this happens on the same threadActually uses time slices interleaved within the

current thread Meant to be used to create non-blocking

operations By convention, async methods should end

with “Async”