Async and Await

For a while the Async and Await commands in c# have confused me.

Like most things the best way to learn about something is to use it in a real world example. I am currently adding an email alert feature to a website. This is an ideal example of something that would benefit from Asynchronous programming. There is no need for the webpage to wait to send 1000s of emails, lets just send a call to get started and allow the browser to carry on as normal.

This is my first try at using async and await so feel free to suggest best practises in the comments.

Lets start with a Send method in my EmailController.

This simply checks to see if you have permission to the page. If not redirects to the login page otherwise it makes a method call and redirects back to the page it came from.

Lets have a look at that method call in more detail.

Task<string> t = SendNotification(id, userid);

SendNotification doesn’t return a normal string it returns a Task<string>, so lets look at how we are creating this.

The return type is set to Task but it has the aysnc keyword appended to it. It also makes a call with the await keyword.

So that is it. My first bit of code that uses Async and Await. My controller calls a method asynchronously which then calls another method asynchronously which sends emails asynchronously.

Async – This enables the Await keyword to be used in the method

Await – This is where things get asynchronous. The await keyword allows the code to wait asynchronously for the long running code to complete.

This post has already been read 738 times!

Simon Foster on GithubSimon Foster on LinkedinSimon Foster on Twitter
Simon Foster
Web Developer
I have worked in SysAdmin and IT Management but now work as a Web Developer. I love everything IT related and I am trying to learn as much as I can especially about DevOps. Why not follow me on twitter?