I was experimenting with how to break out of a ForEachAsync
loop. break
doesn't work, but I can call Cancel
on the CancellationTokenSource. The signature for ForEachAsync
has two tokens - one as a stand-alone argument and one in the Func
body signature.
I took note that when cts.Cancel()
is called, both the token
and t
variables have IsCancellationRequested
set to true. So, my question is: what is the purpose for the two separate token
arguments? Is there a distinction worth noting?
List<string> symbols = new() { "A", "B", "C" };
var cts = new CancellationTokenSource();
var token = cts.Token;
token.ThrowIfCancellationRequested();
try
{
await Parallel.ForEachAsync(symbols, token, async (symbol, t) =>
{
if (await someConditionAsync())
{
cts.Cancel();
}
});
catch (OperationCanceledException oce)
{
Console.WriteLine($"Stopping parallel loop: {oce}");
}
finally
{
cts.Dispose();
}
MyCode
function needs to beasync Task
, notvoid
- and if you do that then you may-as-well just passMyCode
by-name instead of instantiating an identity function (and it annoys me that C# cannot elide identity lambdas...) – Flexor