Async in .NET

1,570 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,570
On SlideShare
0
From Embeds
0
Number of Embeds
265
Actions
Shares
0
Downloads
31
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Async in .NET

  1. 1. What is Async? Synchronous  every line of code is executed in order  the 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
  2. 2. 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
  3. 3. 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
  4. 4. Event-based Async Pattern(EAP) 2nd attempt at Async Uses events to notify when async operations complete  i.e. WebClient.OnDownloadStringCompleted Operation is started with *Async  i.e. WebClient.DownloadStringAsync No IAsyncResult – hard to query current status  Sometimes they have “OnProgress” events
  5. 5. Task Async Pattern Uses Task Parallel Library to wrap APM methods Task.Factory.FromAsync(Begin*, End*, args) Get access to Task functionality  ContinueWith to execute code after operation is complete  ContinueWhenAll to wait for multiple async operations
  6. 6. 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
  7. 7. 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 returns  This will return control to the previous method in the call stack Once async operation returns, control is restored to method and continues as normal
  8. 8. 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 thread  Actually 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”

×