I'm not sure how I'm supposed to mix plinq and async-await. Suppose that I have the following interface
public interface IDoSomething (
Task Do();
}
I have a list of these which I would like to execute in parallel and be able to await the completion of all.
public async Task DoAll(IDoSomething[] doers) {
//Execute all doers in parallel ideally using plinq and
//continue when all are complete
}
How to implement this? I'm not sure how to go from parallel linq to Tasks and vice versa.
I'm not terribly worried about exception handling. Ideally the first one would fire and break the whole process as I plan to discard the entire thing on error.
Edit: A lot of people are saying Task.WaitAll. I'm aware of this but my understanding (unless someone can demonstrate otherwise) is that it won't actively parallelize things for you to multiple available processor cores. What I'm specifically asking is twofold -
if I
awaitaTaskwithin a Plinq Action does that get rid of a lot of the advantage since it schedules a new thread?If I
doers.AsParallel().ForAll(async d => await d.Do())which takes about 5 second on average, how do I not spin the invoking thread in the meantime?
What you're looking for is this:
Using
Task.Runwill use aThreadPoolthread to execute each synchronous part of theasyncmethodDoin parallel whileTask.WhenAllasynchronously waits for the asynchronous parts together that are executing concurrently.This is a good idea only if you have substantial synchronous parts in these
asyncmethods (i.e. the parts before anawait) for example:Otherwise, there's no need for parallelism and you can just fire the asynchronous operations concurrently and wait for all the returned tasks using
Task.WhenAll: