DEV Community

Aaron L Carrick
Aaron L Carrick

Posted on

A Blurb About Async/Await

When using C#'s async/await operators one should not return void unless it's an event. You should always return Task or Task<T>. I'll show you what I mean below.

public async Task PrintItemsToScreenAsync()
{
       foreach(var item in ItemList)
       {
              //Gets name from a database
              item.Name = await GetItemNameAsync();
       }
}

This is an async method, when you don't have any data you want to return you would use the keyword Task. The Task word is saying that you want this method to run async but don't really care about the data, you just want it to do its work and complete.

So how would you call this method from another method?

public async Task CallPrintItemsToScreenAsync()
{
       await PrintItemsToScreenAsync();
       //Other work to do
}

In the code above we make sure to mark the method as async because whenever you want to await a task it needs to be marked as async or else the compiler will yell at you.

What about how to call an async method from an event like a button click?

public async void Button_Click(Object sender, EventArgs e)
{
       await PrintItemsToScreenAsync();
       //Other work to do
}

Take note that when calling from an event you would leave it's return type alone and just mark it async, you would then await the async method needing to be called.

What if I want it to return something like a string?

public async Task<string> PrintItemsToScreenAsync()
{
       foreach(var item in ItemList)
       {
              //Gets name from a database
              item.Name = await GetItemNameAsync();
       }

       return ItemList.Count.ToString();
}

Above we added Task<string>, this means that we must return a value in the form of a string. So we return the string literal of ItemList.Count(). This tells us how many items we worked on. Here's how we could call this.

public async Task GetItemCountAfterDataDownload()
{
       string _results = await PrintItemsToScreenAsync();
       //use _results anywhere you want to show the count
}

Those are just a few tips, I'll be adding more to this but right now it's 1am and I need to sleep :) There is a lot more to cover on async/await, I'll be covering all the basics so stay tuned.

Let me know if you have any questions or if I missed something!

Happy coding!!!

Top comments (0)