So we all love the performance and responsiveness of asynchronous programming… But it sure can be annoying and complicated to write, debug, and maintain your code. In .NET 4 and prior, we had a few choices when doing a significant amount of “work” in your apps:
Synchronous Programming– Duh, this one is not asynchronous.
- Good: Super straight-forward. You’re already doing this.
- Bad: Causes your app to freeze up completely while work is performed. That’s lame.
Thread-based Programming – Uses parallel threads to do background work.
- Good: Fairly easy to code and implement.
- Bad: You usually have to jump through loops to ignore thread safety if you want to do anything meaningful while the background work is processing. And yeah, thread safety is there for a reason… You might find that out the hard way.
Asynchronous Programming Model (APM)– Uses a “begin” and “end” method to manage the async operations.
- Good: Handles threading for you. No more worries about thread safety!
- Bad: Takes a ridiculous amount of complex code. Be prepared to read at least two tutorials to get it right the first time you try.
Event-based Asynchronous Pattern (EAP)– Managing the status of the async operation by using event handlers.
- Good: Easier to implement than APM.
- Bad: Requires extensive event handler creation, raising, and handling. Difficult to maintain because of the strange and excessive code branching.
With Visual Studio 2012 and .NET 4.5, Microsoft introduces a new asychronous programming pattern that lets the compiler do the annoying/complicated work for you. All you need to do is learn two new keywords: async and await. Used right, the new model effectively eliminates APM, EAP, and thread-based models for asynchronous operations.
Here’s how it works:
string content = await BlahBlahBlahAsync();
And that’s it! Behind the scenes it actually returns a Task<type>, which is like a “promise” to eventually deliver a string. The await keyword monitors that and eventually returns the promised type as usual. Your favorite <Whatever>Async() postfix method has already been updated to work with this.
If you want to create your own asynchronous method for use with the await keyword, that’s easy too:
public async Task<string> DoWhateverAsync()
It is a little weird as the return type is Task<type> but you just return type. Despite that, it’s still a slick implementation for asynchronous operations, and a vast improvement on the previous patterns! Enjoy.