I would like to do something like this:
public async Task MyMethod()
{
// Do some preparation
await Parallel.ForEachAsync(0, count, i => { // Do some work //});
// do some finalization
}
However, I did not find an elegant way of doing so. I thought of two ways, but they are sub-optimal:
- The only thing I thought about is manually partitioning the range, creating tasks, and then using Task.WhenAll.
- Using the following code
Task.Factory.StartNew(() => Parallel.For(...));
.
The problem is that it "wastes" a thread on the asynchronous task. - Using TPL Dataflow's ActionBlock, and posting the integers one by one. The drawback is that it does not partition the range in a smart way like Parallel.For does, and works on each iteration one by one.
- Manually using a Partitioner with Partitioner.Create, but it is less elegant. I want the framework to do intelligent partitioning for me.