Async and Await: An Explanation

DZone 's Guide to

Async and Await: An Explanation

I've always been confused by the Async and Await command in C#. But finally, I'm having an easier time remembering the differences! And you can, too.

· Database Zone ·
Free Resource

For a while now, 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 thousands of emails; let's 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 practices in the comments.

Let's start with a Send method in my EmailController.

public ActionResult Send(int id, int pageId, int userID)
  if (!Authorize.checkPageIsAuthorised(userID, (Authorize.PageIds)pageId))
    return Redirect("/login");
    Task<string> t = SendNotifications(id,userID);
    return Redirect(Request.UrlReferrer.ToString());

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.

Let's 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 let's look at how we are creating this.

public async Task<string> SendNotifications(int id,string type,int userid)
            //logic ommitted
            await ef.SendEmail(model, emailHtmlBody);
            return "OK";

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.

public async Task SendEmail(EmailModel model,string emailHtmlBody)
        //logic removed
        await smtp.SendMailAsync(message);

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.

database ,async ,await ,c#

Published at DZone with permission of Simon Foster , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}