How to modify the following code and make it runs multiple tasks concurrently?
foreach (SyndicationItem item in CurrentFeed.Items)
{
if (m_bDownloadInterrupted)
break;
await Task.Run( async () =>
{
// do some downloading and processing work here
await DoSomethingAsync();
}
}
I also need to make interruption and stop the process possible. Because my DoSomethingAsync method reads the tag (a global boolean value) to stop the process.
Thanks
No, that won't run them concurrently - you're waiting for each one to finish before starting the next one.
You could put the results of each Task.Run
call into a collection, then await Task.WhenAll
after starting them all though.
(It's a shame that Parallel.ForEach
doesn't return a Task
you could await. There may be a more async-friendly version around...)
This will process the items concurrently.
Parallel.ForEach(CurrentFeed.Items, DoSomethingAsync)
To be able to cancel you can need a CancellationToken.
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
// Add the ParallelOptions with the token to the ForEach call
Parallel.ForEach(CurrentFeed.Items,po ,DoSomethingAsync)
// set cancel on the token somewhere in the workers to make the loop stop
cts.Cancel();
For detail see (among other sources) http://msdn.microsoft.com/en-us/library/ee256691.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With