[release/6.0] Fix corner-case handling of cancellation exception in ForEachAsync #59236
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Backport of #59065 to release/6.0
/cc @stephentoub
Customer Impact
If the body of a Parallel.ForEachAsync loop throws an OperationCanceledException using the supplied CancellationToken and it hasn't had cancellation requested, the Task returned from ForEachAsync will never complete and the calling code will effectively hang, e.g.
This is not a common thing to do. However, if you do happen to do it, your app will hang. The code is filtering out such exceptions, but if they're the only ones, it ends up filtering out all of them, causing the call that would have completed the returned Task to throw an exception which is then inadvertently eaten.
The fix is to change the design to simply not do such filtering: all exceptions thrown in such a case will be stored in the task.
Testing
Additional unit tests.
Risk
Relatively low.
awaitthe returned task, which this won't affect, as await only throws the first exception stored in the task.