4

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

2 Answers 2

9

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...)

Sign up to request clarification or add additional context in comments.

4 Comments

sorry, I have await inside that task. forget to put it in. Then how could I resolve this problem? Thanks.
@Jon: Parallel.ForEach uses the calling thread as one of its parallel threads, so you can make it async-friendly by wrapping it in Task.Run.
@Jerry: Task.Run will work as expected with asynchronous lambdas as well as synchronous lambdas (it unwraps the asynchronous ones). So you can still put the results into a collection and then await Task.WhenAll.
@StephenCleary: Good point - it feels a little icky, but it would be considerably nicer than collecting the tasks manually.
1

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

1 Comment

Sorry, but how to interrupt and stop the process based on the method you provide? Because my DoSomethingAsync method reads tag to stop the process. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.