Asynchronous I/O in .NET
What is Async I/O? Executing I/O in the background, allowing foreground work to proceed I/O executes and completes in parallel with, and independent of, the application that initiated it Called “Overlapped I/O” in Win32
What is Async I/O? Synchronous I/O Asynchronous I/O Start I/O Blocked Process Asynchronous I/O Start I/O Blocked Process Background I/O Background I/O
Why use Async I/O? Scalability Throughput Threads are expensive Non-blocking UI Silverlight
Why not Async I/O? Complexity Debuggability Unnecessary?
Asynchronous Programming Model Standard pattern for async work in .NET 3.5 Convert: string DoOperation(int param1, double param2); Into: IAsyncResult BeginDoOperation(int param1, double param2, AsyncCallback callback, object state); string EndDoOperation(IAsyncResult asyncResult); In WCF, use [OperationContract(AsyncPattern = true)]
Asynchronous Programming Model Four ways to complete asynchronous call: Supply an AsyncCallback Poll IAsyncResult.IsCompleted Wait on IAsyncResult.AsyncWaitHandle (blocking) Call EndXxx method (blocking) Always call EndXxx method!
Asynchronous I/O with APM in .NET 3.5 Demo
Event-Based Pattern Introduced in .NET 2.0 to simplify APM E.g., PictureBox, SoundPlayer, WebClient MethodAsync method MethodCompleted event CancelAsync method Uses AsyncOperationManager internally
Task Parallel Library New framework for parallel and async work in .NET 4.0 Convert: string DoOperation(int param1, double param2); Into: Task<string> DoOperation(int param1, double param2);
Task Parallel Library Two ways to complete asynchronous call: ContinueWith Call Task<T>.Result or Task.Wait (blocking)
Task Parallel Library Wrap existing APM method IAsyncResult BeginDoOperation(int param1, double param2, AsyncCallback callback, object state); string EndDoOperation(IAsyncResult asyncResult); with FromAsync: Task<string>.Factory.FromAsync(BeginDoOperation, EndDoOperation, int param1, double param2, object state);
Asynchronous I/O with TPL in .NET 4.0 Demo
Where to? ASP.NET Asynchronous Pages (http://msdn.microsoft.com/en-us/magazine/cc163725.aspx) IHttpAsyncHandler (http://msdn.microsoft.com/en-us/magazine/cc163463.aspx) F# Async Workflows (http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx) Reactive Extensions for .NET (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) Axum (http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx) http://github.com/bgrainger/AsyncIoDemo