Sobes.tech
Junior — Middle

How can you stop the execution of an asynchronous Task without terminating the program or interrupting the execution process?

sobes.tech AI

Answer from AI

In C#, to stop the execution of an asynchronous Task without terminating the entire process, the common mechanism is to use cancellation via a CancellationToken. The Task itself cannot simply be "stopped" from outside, but a cancellation token can be passed to the task, which the task periodically checks and then terminates correctly upon a cancellation request.

Example of using CancellationToken:

CancellationTokenSource cts = new CancellationTokenSource();

async Task DoWorkAsync(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        // Perform work
        await Task.Delay(1000);
    }
    // Cleanup or finish
}

// Starting the task
var task = DoWorkAsync(cts.Token);

// Later, to cancel
cts.Cancel();

await task; // Wait for completion

Thus, the task itself controls the moment of completion, reacting to the cancellation signal.