Sobes.tech
Middle+

How to correctly implement cancellation of a reservation when tasks are executed in parallel using Task.WhenAll?

sobes.tech AI

Answer from AI

When executing tasks in parallel using Task.WhenAll, to properly cancel the booking, you should use a CancellationToken. It allows coordinating the cancellation of all tasks.

Example:

public async Task CancelBookingsAsync(List<Booking> bookings, CancellationToken cancellationToken)
{
    var tasks = bookings.Select(async booking =>
    {
        cancellationToken.ThrowIfCancellationRequested();
        await CancelBookingAsync(booking, cancellationToken);
    });

    try
    {
        await Task.WhenAll(tasks);
    }
    catch (OperationCanceledException)
    {
        // Cancellation handling logic
        Console.WriteLine("Booking operations cancellation completed.");
    }
}

public async Task CancelBookingAsync(Booking booking, CancellationToken cancellationToken)
{
    // Simulate booking cancellation
    await Task.Delay(1000, cancellationToken);
    Console.WriteLine($"Booking {booking.Id} canceled");
}

Key points:

  • Pass the same CancellationToken to all tasks.
  • Inside each task, check cancellationToken.ThrowIfCancellationRequested() for timely cancellation.
  • Call CancellationTokenSource.Cancel() if you need to initiate cancellation.

This approach guarantees that when cancellation occurs, one task will interrupt execution, and the remaining tasks will also be able to complete correctly.

How to correctly implement cancellation of a… - sobes.tech