250 likes | 585 Views
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.
E N D
Asynchronous Programmingwith .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 • “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------|
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
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
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();}
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); }}
Downfalls of Previous Patterns • A lot of extra code • Difficult to… • Read • Write • Maintain • Debug
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
.NET 4.5 Framework • Keywords • “Async” • “Await” • Return Type of Object Task • Task if sub or void • Task<TResult> • Naming Convention • MethodNameAsync()
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; }
Using New Keywords • Mark async method with Async or async • Marked method can use Await or await
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; }
Asynch Method Flow of Control Source: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
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
Demo • Asynchronous • Multi-Threaded