Blog Logo
TAGS

C# 5 Async Exception Handling

At the PDC 2010 conference, Microsoft showed their proposed asynchronous features for C# 5. There’s one particular feature I want to examine: error handling. Anders Hejlsberg showed this, but he did so fairly quickly. The feature is so elegant that it’s easy to overlook what it does for you, so I thought it would be worth a closer look.The broad theme of the new async features is that you can write code that looks just like normal code, but which works asynchronously. For example:private async void FetchData() { using (var wc = new WebClient()) { try { string content = await wc.DownloadStringTaskAsync( new Uri(http://www.interact-sw.co.uk/oops/)); textBox1.Text = content; } catch (WebException x) { textBox1.Text = Error: + x.Message; } } } Most of this seems fairly ordinary—we’re using the WebClient class to download some text via HTTP, putting the result in a TextBox. (I tested this out in a WPF application, but it would also work in Windows Forms.) We have some exception handling, most obviously the catch block to handle a WebException. There’s no web page with the specified URL, so the server will respond with a 404 HTTP error, meaning we’ll definitely get an exception. But that’s not the only exception-related code: more subtly, there’s a using block to ensure that we Dispose the WebClient even in the face of exceptions. (As far as I can tell, WebClient doesn’t actually do anything in its)