Junior — Middle
Explain the differences between the keywords async and await when working with asynchronous programming.
sobes.tech AI
Answer from AI
The keyword async is used to declare a method as asynchronous, meaning it can execute without blocking the calling thread and return a result in the future (usually Task or Task<T>).
The keyword await is used inside an asynchronous method to suspend execution until the asynchronous operation completes, without blocking the thread, and control is returned to the caller.
Example:
public async Task<int> GetDataAsync()
{
int result = await SomeLongRunningOperationAsync();
return result;
}
Here, async indicates that the method is asynchronous, and await means that execution will wait for SomeLongRunningOperationAsync to complete without blocking the thread.