async in .net
TRANSCRIPT
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
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
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
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
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
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
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
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”