简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM