Having this handler :
public async Task<Result> Handle(MyQuery request, CancellationToken cancellationToken)
{
var cancellationTokenSource = new CancellationTokenSource();
await Parallel.ForEachAsync(myList, async (objectId, _) =>
{
var result = await _service.GetObject(objectId);
if (result.Any())
{
cancellationTokenSource.Cancel();
}
});
if (cancellationTokenSource.IsCancellationRequested) return Result.Fail("Error message.");
return Result.Ok();
}
This works, but was wondering if I'm using CancellationTokenSource correct here?
You are using
CancellationTokenSourcejust as a boolean variable, if the goal is to cancel the batch when some condition is met then the usage is completely wrong, you need to pass token to theForEachAsynccall (and ideally handle cancellation token in the body). Something along these lines:And as @Magnus correctly points out - you should use the cancellation token passed to your
Handlemethod (CancellationToken cancellationToken) also:See also: