Junior — Middle
How are asynchronous operations performed in a program?
sobes.tech AI
Answer from AI
In C#, asynchronous operations are performed using the keywords async and await, which allow writing code that does not block the main thread.
Mechanism:
- The method is marked as
asyncand returnsTaskorTask<T>. - Inside the method,
awaitis used to call asynchronous operations. - When
awaitis encountered, the execution of the method is suspended, and control is returned to the calling code. - When the asynchronous operation completes, the method resumes execution from the
awaitpoint.
Example:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
Console.WriteLine("Start");
await DelayExample();
Console.WriteLine("End");
}
static async Task DelayExample()
{
await Task.Delay(1000); // asynchronous delay for 1 second
Console.WriteLine("Delay completed");
}
}
This approach allows efficient resource utilization without blocking threads, which is especially important for UI and server applications.