0 day streak
csharp / beginner
Snippet

Executing Tasks with Await

The async and await keywords allow you to write code that performs long-running tasks without freezing the program. It enables asynchronous programming, which is essential for responsive applications.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Threading.Tasks;
public class Program {
public static async Task Main() {
Console.WriteLine("Starting...");
await PerformDelayedTask();
Console.WriteLine("Done!");
}
static async Task PerformDelayedTask() {
// Simulate work without blocking the thread
await Task.Delay(1000);
}
}
Breakdown
1
async Task Main()
Declares an entry point that can wait for asynchronous operations.
2
await Task.Delay(1000)
Pauses the method execution for 1000 milliseconds without blocking the main thread.