Async layer
Set up data flow using async/await and Task.
Async layer
Now we make the command async. Instead of ICommand.Execute() we use Task<string> ExecuteAsync(). The command can then do long work (network, file I/O) without blocking the calling thread.
Main also becomes async: static async Task Main(). The call is awaited with await cmd.ExecuteAsync(). This small change lays the ground for adding real async work later (say, fetching from the network).
async Task Main
Since C# 7.1 Main can be async: static async Task Main(). This allows await and removes the need for clunky workarounds like GetAwaiter().GetResult().
Inside an async method await waits for each call. In HelloCommand.ExecuteAsync(), await Task.CompletedTask awaits an already-completed Task; this is skeleton code standing in for real async work. Later you can replace it with a network or file call.
Exercise Make the command async
Make the ICommand interface async: it has a Task<string> ExecuteAsync() method. HelloCommand.ExecuteAsync() has the signature async Task<string>, calls await Task.CompletedTask, and returns "Merhaba". Make Main static async Task Main() and print the result via await cmd.ExecuteAsync().
Show example solution
Write interface ICommand { Task<string> ExecuteAsync(); }. Write class HelloCommand : ICommand { public async Task<string> ExecuteAsync() { await Task.CompletedTask; return "Merhaba"; } }. Make Main: static async Task Main() { var cmd = new HelloCommand(); Console.WriteLine(await cmd.ExecuteAsync()); }.
Example solution:
using System;
using System.Threading.Tasks;
interface ICommand
{
Task<string> ExecuteAsync();
}
class HelloCommand : ICommand
{
public async Task<string> ExecuteAsync()
{
await Task.CompletedTask;
return "Merhaba";
}
}
class Program
{
static async Task Main()
{
var cmd = new HelloCommand();
Console.WriteLine(await cmd.ExecuteAsync());
}
}
Test yourself
-
What return type should an async command method have?
- string
- Task<string>
- void
- int
Show answer
Task<string> — Correct. Task<string> lets you await a string result from an async method.
-
Complete the async Main declaration
static ____ Task Main() { Console.WriteLine(await cmd.ExecuteAsync()); }Show answer
static async Task Main() { Console.WriteLine(await cmd.ExecuteAsync()); } -
Match async concepts
- Task<string>
- Async return type
- await
- Waits for a Task
- async Task Main
- Async entry point
- Task.CompletedTask
- Already-completed Task