Defining async methods
Learn to define async methods and await them.
Defining an async method
An async method is declared by placing async at the start: static async Task Show(). Inside you can use await; this runs the method on a separate flow awaited by callers.
Async methods that return no value return Task; those that return a value return Task<T>. Avoid async methods returning void; they are reserved for event handlers.
async Task Main
Since C# 7.1 the Main method can be declared as async Task. This lets you use await at the program entry point directly, with no need for wrappers like GetAwaiter().GetResult().
Declaration: static async Task Main(). Any async method called with await can be awaited right here. This is the cleanest way to try async in console apps.
Exercise async method and async Main
Define static async Task<string> GetName(). In its body write await Task.CompletedTask and return "Alex";. Make Main a static async Task Main; read the result with await GetName() and print it with Console.WriteLine.
Show example solution
In the body write await Task.CompletedTask and return "Alex". Make Main static async Task Main() and write string name = await GetName(); Console.WriteLine(name);
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static async Task<string> GetName()
{
await Task.CompletedTask;
return "Alex";
}
static async Task Main()
{
string name = await GetName();
Console.WriteLine(name);
}
}
Test yourself
-
What is the recommended return type for async methods?
- Task or Task<T>
- void
- Thread
- IEnumerable<T>
Show answer
Task or Task<T> — Correct. Async methods should return Task or Task<T>.
-
Complete the async declaration
static ____ Task Show() { await Task.CompletedTask; }Show answer
static async Task Show() { await Task.CompletedTask; } -
When is async void used?
- Always; async methods must return void
- Only in event handlers
- Never; it is not valid
- Only in test methods
Show answer
Only in event handlers — Correct. async void is only for event handlers.