1 / 16

Asynchronous Programming with .NET 4.5

Asynchronous Programming with .NET 4.5. Cole Durdan. Topics of Discussion. What is asynchronous programming? Previous patterns Task Based Async Programming .NET 4.5 Keywords What happens in an async . method? Demo. Asynchronous Programming.

deo
Download Presentation

Asynchronous Programming with .NET 4.5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Asynchronous Programmingwith .NET 4.5 Cole Durdan

  2. Topics of Discussion • What is asynchronous programming? • Previous patterns • Task Based Async Programming • .NET 4.5 Keywords • What happens in an async. method? • Demo

  3. Asynchronous Programming • “Asynchronous” means API does not block calling thread • Multithreading? • Not Necessarily • Doesn’t lock UI on large computations Synchronous: |----A-----| |-----B-----------| |-------C------| Asynchronous: |----A-----| |-----B-----------| |-------C------|

  4. When to Use Async. Programming • Web Access • Database Requests • Working with files • Working with images • WCF programming • Working with sockets • With UI that need to be responsive

  5. Previous Asynchronous Patterns • The Asynchronous Programming Model (APM) • BeginMethodName and EndMethodName • IAsyncResult • Keep track of states • The Event based Asynchronous Pattern (EAP) • Assigns delegates to event handlers that are invoked when an event is triggered • introduced in the .NET Framework version 2.0

  6. APM CopyTo() Example • public static IAsyncResultBeginCopyTo(Stream source, Stream destination){vartcs = new TaskCompletionSource();byte[] buffer = new byte[0x1000];Action<IAsyncResult> readWriteLoop = null;readWriteLoop = iar =>{try{      for (boolisRead = iar == null; ; isRead = !isRead){switch (isRead){case true:iar = source.BeginRead(buffer, 0, buffer.Length, readResult =>{if (readResult.CompletedSynchronously) return;readWriteLoop(readResult);}, null);if (!iar.CompletedSynchronously) return;break;case false:intnumRead = source.EndRead(iar);if (numRead == 0){tcs.TrySetResult(true);return;}iar = destination.BeginWrite(buffer, 0, numRead, writeResult =>{try{if (writeResult.CompletedSynchronously) return;destination.EndWrite(writeResult);readWriteLoop(null);}catch(Exception e) { tcs.TrySetException(e); }}, null);if (!iar.CompletedSynchronously) return;destination.EndWrite(iar);break;}}}}catch(Exception e) { tcs.TrySetException(e); }};readWriteLoop(null);return tcs.Task;}public static void EndCopyTo(IAsyncResultasyncResult){((Task)asyncResult).Wait();}

  7. TAP CopyTo() Example public static async void CopyToAsync(Stream source, Stream destination){ byte[] buffer = new byte[0x1000];intnumRead; while((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0) { await destination.WriteAsync(buffer, 0, numRead); }}

  8. Downfalls of Previous Patterns • A lot of extra code • Difficult to… • Read • Write • Maintain • Debug

  9. Task-based Asynchronous Pattern (TAP) • Relies on the Task Parallel Library (TPL) • System.Threading • System.Threading.Task namespace • Introduced in .NET 4.0 Framework • New support in 4.5 • TPL is the preferred way to write multithreaded and parallel code

  10. .NET 4.5 Framework • Keywords • “Async” • “Await” • Return Type of Object Task • Task if sub or void • Task<TResult> • Naming Convention • MethodNameAsync()

  11. Using New Keywords Synchronous Method: intGetInt() { int number = GetNumber(); DoIndependentWork(); return number; } Asynchronous Method: async Task<int> GetIntAsync() { Task<int> getNumTask = GetNumberAsync(); DoIndependentWork(); int number = await getNumTask return number; }

  12. Using New Keywords • Mark async method with Async or async • Marked method can use Await or await

  13. Asynch Method Flow of Control async Task<int> AccessTheWebAsync() { HttpClientclient = new HttpClient(); Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); DoIndependentWork(); string urlContents = await getStringTask; return urlContents.Length; }

  14. Asynch Method Flow of Control Source: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

  15. References • http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx • http://blogs.msdn.com/b/dotnet/archive/2012/04/03/async-in-4-5-worth-the-await.aspx • http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45 • http://www.dotnetperls.com/async • http://www.codeproject.com/Tips/591586/Asynchronous-Programming-in-Csharp-5-0-using-async

  16. Demo • Asynchronous • Multi-Threaded

More Related