You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.

Asynchronous Programming

Armed with a firm understanding of threads, you can now look at how you can begin writing asynchronous programs for .NET.

Asynchronous programming is when you begin an operation on a background thread to execute concurrently, and have it terminate at some later time, either ignoring the new task to complete in the background or polling it at a later time to check on its return value.

Modern hardware has facilities for parallel reading and writing, so performing asynchronous IO may improve your application’s performance. This is especially true if you are writing data to disk that you will not need later—there is no need to “block” the program, waiting for the operation to complete, when you can begin the write asynchronously and continue execution of your program.

The way asynchronous programs have historically been written on .NET has been using the asynchronous programming model, or APM.

The APM is a pattern for dividing asynchronous operations into two methods called BeginOperation and EndOperation. When BeginOperation is called, the operation will begin asynchronously, and when complete will execute a provided delegate callback. The code within that callback must call EndOperation, which will retrieve the result of the asynchronous computation. Coordination, such as polling for when the operation has completed, happens through the use of the IAsyncResult interface.

Example 11-5 uses the APM to asynchronously open a file, perform some operation on the file’s ...

The best content for your career. Discover unlimited learning on demand for around $1/day.