Barrier with an async postPhaseAction in C#

140 Views Asked by At

I need to use an async method as the postPhaseAction of Barrier, for different reasons, including the ability to cancel the method. In the following example, the postPhaseAction saves items in a list to a database, which can cooperate with the cancellation request.

var entities = new ConcurrentQueue<string>();
var barrier = new Barrier(0, async (_) =>
{
    var context = GetDatabaseContext();
    await context.Entities.AddRangeAsync(entities, cancellationToken);
    await context.SaveChangesAsync(cancellationToken);
}

The issue with this approach is that the barrier does not wait for the postPhaseAction to conclude, which can result in concurrently running multiple delegations of postPhaseAction.

1

There are 1 best solutions below

3
Paulo Morgado On

The Barrier class takes an Action which has a void return value and cannot be awaited.