Sobes.tech
Middle

Kuidas töötab asünkroonne meetod C#-s?

sobes.tech AI

Vastus AI-lt

Asynchronous method in C# allows performing operations that may take a long time (e.g., input/output, network requests) without blocking the main execution thread.

When calling an asynchronous method marked with the async keyword, control is transferred to the caller until the asynchronous operation completes. The operation runs in the background (e.g., using a thread pool or system I/O mechanisms).

The await keyword inside an asynchronous method indicates where the asynchronous operation can be paused. When execution reaches await, control returns to the caller, and the continuation of the method is scheduled to run when the awaited operation completes.

The result of the asynchronous operation (or exception) is then passed back to the continuation of the async method, where it is handled. The state of the asynchronous method is automatically managed by the C# compiler, which transforms it into a state machine.

public async Task<string> GetDataAsync(string url)
{
    // Simulating a long input/output operation
    using (var httpClient = new HttpClient())
    {
        string result = await httpClient.GetStringAsync(url); // await: method execution can be paused
        return result;
    }
}

// Example of calling an asynchronous method
public async Task ProcessDataAsync(string url)
{
    Console.WriteLine("Starting data download...");
    string data = await GetDataAsync(url); // Waiting for the async operation to complete
    Console.WriteLine("Data loaded: " + data.Length + " characters.");
}