csharp / beginner
Snippet
Asynchronous Task Suspension
The async and await keywords allow you to write code that performs long-running operations without freezing the entire application. Task.Delay mimics a background job like fetching data.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
using System;using System.Threading.Tasks;public class AsyncDemo{public async Task ExecuteDelayedTask(){// Suspend execution for 1 second without blocking the threadawait Task.Delay(1000);Console.WriteLine("Task resumed after delay.");}}
Breakdown
1
public async Task ExecuteDelayedTask()
Defines an asynchronous method that returns a Task object.
2
await Task.Delay(1000);
Pause execution here until the 1000ms timer completes, freeing up the thread.