Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run multiple tasks in C#?

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

like image 962
Jerry Avatar asked Dec 26 '22 18:12

Jerry


2 Answers

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

like image 146
Jon Skeet Avatar answered Dec 29 '22 09:12

Jon Skeet


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

like image 29
IvoTops Avatar answered Dec 29 '22 10:12

IvoTops