Sobes.tech
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 async and returns Task or Task<T>.
  • Inside the method, await is used to call asynchronous operations.
  • When await is 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 await point.

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.

How are asynchronous operations performed in a… - sobes.tech