Anonymous methods + Async = hell yeah

By | July 9, 2012

I’m a huge fan of C# 4.5’s new async/await keywords, and if you haven’t played with the Async CTP (for C# 4.0) I highly suggest you do so, especially if you’re doing mobile dev. If you are, you know that there’s no synchronous call off WebClient (to make web service calls) and in Windows 8 Microsoft even went a step further. Damn near every single thing you do is asynchronous. Their benchmark for whether or not an operation got Async/Sync or just Async was (something like) if it took more than 100ms to complete, it got Async only.
That’s a lot of stuff.

If you’re a fan of all the latest things in C#, you’re probably a fan of anonymous methods. If you’ve never heard the term, chances are you’ve at least seen them, or maybe implemented them, just without knowing their name:

					notificationChannel.ChannelUriUpdated += (sender, e) => PushNotificationUri = e.ChannelUri;

That right there’s an anonymous method. Normally you’d see the good ol’ “new EventHandler…” blah blah, but isn’t this just so much prettier?
Where am I going with this, perhaps you can tell. What if I was making some web service call inside my anonymous method, and wanted to take advantage of the new ‘await’ functionality?

				ConnectedExecution.Run(() =>
				{
					var authClient = new GZipWebClient();
					var authResponse = await authClient.DownloadStringTaskAsync("http://.....");
				});

The above code won’t compile.
(see my earlier post if you don’t know what ConnectedExecution is, and read this post by Jeff Wilcox on GZipWebClient and why you should be using it in your mobile apps)
Why? Part of the async/await paradigm is that you have to put your ‘await’ statement within a method marked as ‘async’.
When I first hit this my first reaction was “damn. there goes that.” then I had a thought…

				ConnectedExecution.Run(async () =>
				{
					var authClient = new GZipWebClient();
					var authResponse = await authClient.DownloadStringTaskAsync("http://.....");
				});

and voila. Works. Basically what this proved to me is that you can put the ‘async’ modifier in front of any method, no matter the “kind” and it works.
Awesome.