Reputation: 151
I am getting this as an error in Visual Studio 2022
Avoid unsupported fire-and-forget async-void methods or delegates. Unhandled exceptions will crash the process.
Having a lot of trouble finding anything on this. The code is working 100% fine but I would like to avoid this error without disabling it if I can. The code line is along these terms.
Parallel.ForEach(things, async (thing) => await ProcessThing(thing));
Upvotes: 2
Views: 464
Reputation: 151
Credit to theodor for pointing me to the underlying code issue addressed here in detail Parallel foreach with asynchronous lambda
The simple answer is that it is very unlikely your intention to start a bunch of back ground task by feeding Parallel.ForEach an async lambda, then continue the main thread. It will fire them off then continue the main thread likely not completing all the work you desire. Long story short Paralell.ForEach + async = Bad, try something else. The error from visual studio here is detecting a fire-and-forget, but it would be really help to call out risks associated with that such as not finishing the work as well as potentially crashing the process at a later point on the main thread. Below is what I chose as it is the most direct simple change from the old to the new.
var options = new ParallelOptions {
MaxDegreeOfParallelism = 10,
CancellationToken = CancellationToken.None
};
await Parallel.ForEachAsync(things, options, async (thing, cancellationToken) => await ProcessThing(thing));
What might help this click is to view each "await" word as, stop here until this is done, with the original version (Paralell.ForEach) lacking that it simply continues after creating each of the tasks and not waiting on them to finish.
Upvotes: 3