Tuesday, April 18, 2023

How do you use async/await in .NET Core?

Async/await is a programming pattern in .NET Core that allows you to write asynchronous code in a more readable and manageable way. Here's an example of how to use async/await in .NET Core:

public async Task<int> CalculateSumAsync(int a, int b)
{
    int sum = await LongRunningCalculationAsync(a, b);
    return sum;
}

public async Task<int> LongRunningCalculationAsync(int a, int b)
{
    await Task.Delay(1000); // Simulate long running operation
    return a + b;
}



In this example, the CalculateSumAsync method is marked with the async keyword, which indicates that it contains asynchronous code. The method returns a Task<int> instead of an int to indicate that it is an asynchronous operation that will complete at some point in the future.

The LongRunningCalculationAsync method is also marked with the async keyword, and contains a call to the Task.Delay method to simulate a long running operation. The await keyword is used to indicate that the method should wait for the Task.Delay operation to complete before returning the result.

To use the CalculateSumAsync method, you can simply call it like this:

int sum = await CalculateSumAsync(2, 3);


The await keyword is used again to indicate that the calling method should wait for the CalculateSumAsync operation to complete before continuing.

Overall, async/await is a powerful and flexible pattern in .NET Core that allows you to write efficient and responsive code that can handle long-running operations without blocking the calling thread.

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.