1

Why does this code result in a compiler error:

await Parallel.ForEachAsync(files, loopOptions, async (file, CancellationToken.None) =>

but this code snippet does not?

var x = CancellationToken.None;

await Parallel.ForEachAsync(files, loopOptions, async (file, x) =>

Am I not better off with

await Parallel.ForEachAsync(files, loopOptions, async (file, _) =>

1 Answer 1

5

When you write a lambda expression as async (list of identifiers) => body, the identifiers are parameter names. What you've written to start with is a little bit like trying to write a method declaration as:

public static async Task Method(string file, CancellationToken CancellationToken.None)

which clearly wouldn't work.

Note that in your second example:

var x = CancellationToken.None;

await Parallel.ForEachAsync(files, loopOptions, async (file, x) =>

... you've got two separate x variables... the local variable you've declared in the first line, and then the parameter you've declared in the lambda expression.

Fundamentally, you don't get to specify what the value is when you provide a lmabda expression... the value is passed in by the caller. (In this case, what Parallel.ForEachAsync does might be complicated, based on ParallelOptions - and its own internal cancellation token used to allow a failure in one call to cancel others.)

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah need to understand the signature. Tired eyes, thanks.
Maybe worth mentioning: OP uses an overload with ParallelOptions. So, they could set a specific token in its properties.
@Fildor: Done, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.