简体   繁体   English

如何在C#中运行多个任务?

[英]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. 因为我的DoSomethingAsync方法读取标记(一个全局布尔值)来停止进程。

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. 您可以将每个Task.Run调用的结果放入一个集合中,然后启动它们之后等待Task.WhenAll

(It's a shame that Parallel.ForEach doesn't return a Task you could await. There may be a more async-friendly version around...) (遗憾的是Parallel.ForEach没有返回你可以等待的Task 。可能有一个更加异步友好的版本......)

This will process the items concurrently. 这将同时处理这些项目。

  Parallel.ForEach(CurrentFeed.Items, DoSomethingAsync)

To be able to cancel you can need a CancellationToken. 要取消,您可能需要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 有关详细信息,请参阅(以及其他来源) http://msdn.microsoft.com/en-us/library/ee256691.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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