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:

  1. Synchronous Programming– Duh, this one is not asynchronous.

    1. Good: Super straight-forward. You’re already doing this.
    2. Bad: Causes your app to freeze up completely while work is performed. That’s lame.
  2. Thread-based Programming – Uses parallel threads to do background work.

    1. Good: Fairly easy to code and implement.
    2. 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.
  3. Asynchronous Programming Model (APM)– Uses a “begin” and “end” method to manage the async operations.

    1. Good: Handles threading for you. No more worries about thread safety!
    2. 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.
  4. Event-based Asynchronous Pattern (EAP)– Managing the status of the async operation by using event handlers.

    1. Good: Easier to implement than APM.
    2. 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()
 return“All done!”;

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.

Like this post? Share it!
Free WordPress Themes, Free Android Games