Sobes.tech
Junior — Middle

How can the execution of an asynchronous operation be completed?

sobes.tech AI

Answer from AI

In C#, an asynchronous operation automatically completes when the end of a method marked with the async keyword is reached, or when a result is returned (for example, via return). If you need to prematurely complete an asynchronous operation, you can use:

  • Returning a result via return.
  • Throwing an exception to interrupt execution.
  • Cancellation through CancellationToken, if the operation supports cancellation.

Example of early termination with CancellationToken:

async Task DoWorkAsync(CancellationToken token)
{
    for (int i = 0; i < 10; i++)
    {
        token.ThrowIfCancellationRequested();
        await Task.Delay(1000);
    }
}

Thus, the completion of an asynchronous operation is controlled either by the method's logic or an external cancellation signal.