The
asynchronous programming in .NET is supported through a use of BeginXXX and EndXXX methods. Operations are started by calling the BeginXXX which begins
the operation and then returns. The programmer must also call the EndXXX method to be notified that the asynchronous operation has ended. Nevertheless, most programmers prefer to use synchronous over asynchronous programming. In my opinion there are two reasons for that. First is that there are many .NET classes which only have support for synchronous programming and the second is that synchronous programming is generally speaking simpler then asynchronous programming. The catch is in a fact that simpler isn't always the better, because in many case the asynchronous
programming model can produce more responsive and more scalable applications.
There is an interesting MSDN article by Jeffery Richter about implementing the CLR asynchronous programming model, but if you take a look at the code you will see that it's pretty complicated and hardly understandable on the first look. Luckily Microsoft has provided us with F# programming language which has some cool and powerful features. One of them are asynchronous expressions. To demonstrate how they are used, I wrote a simple FriendFeed client for fetching and displaying user's home feed.
[<AutoOpen>]
module WebRequestExtensions =
type System.Net.WebRequest with
member x.AsyncGetRetResponse() = Async.BuildPrimitive(x.BeginGetResponse,
x.EndGetResponse)
let (!!) : string -> XName = XName.op_Implicit
type FriendFeedStatus = { Title : string; User : string; Service : string }
let printTimeline nickName password (url:string) =
async { let request = WebRequest.Create url :?> HttpWebRequest
do request.Credentials <- new NetworkCredential(nickName, password)
use! reqResponse = request.AsyncGetRetResponse()
use streamReader = new StreamReader(reqResponse.GetResponseStream())
let! xml = streamReader.AsyncReadToEnd()
let xmlDocument = XDocument.Parse xml
let entries = xmlDocument.Root.Elements(!! "entry")
for entry in entries do
Console.WriteLine("{0} via {1}: {2}",
entry.Element(!! "user").Element(!! "nickname").Value,
entry.Element(!! "service").Element(!! "id").Value,
entry.Element(!! "title").Value)}
We can see that the code is concise and quickly understandable if we are familiar with the basic F# concepts. We can call the defined function with the following code snippet:
Async.Start (printTimeline "your_nickname"
"your_remotekey"
"http://friendfeed.com/api/feed/home?format=xml")
which will start the asynchronous computation in the thread pool and will not wait its result. Beside the asynchronous expressions it's used one more interesting feature. That's the LINQ to XML and Matthew Podwysocki's "!!" operator which he calls "Convert Dammit" operator. This operator is used to implicitly convert a string to a XName (note that there is no need to write this operator in C#).