C# 如何实现多线程并行执行多个任务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18227430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement multi-threading and parallel execute several tasks?
提问by Aakash
I am new to threaded programming. I have to run few tasks in PARALLEL and in Background (so that main UI execution thread remain responsive to user actions) and wait for each one of them to complete before proceeding further execution.
我是线程编程的新手。我必须在 PARALLEL 和后台运行几个任务(以便主 UI 执行线程保持对用户操作的响应)并等待每个任务完成,然后再继续执行。
Something like:
就像是:
foreach(MyTask t in myTasks)
{
t.DoSomethinginBackground(); // There could be n number of task, to save
// processing time I wish to run each of them
// in parallel
}
// Wait till all tasks complete doing something parallel in background
Console.Write("All tasks Completed. Now we can do further processing");
I understand that there could be several ways to achieve this. But I am looking for the best solution to implement in .Net 4.0 (C#).
我知道有几种方法可以实现这一目标。但我正在寻找在 .Net 4.0 (C#) 中实现的最佳解决方案。
采纳答案by Nolonar
To me it would seem like you want Parallel.ForEach
对我来说,这似乎是你想要的 Parallel.ForEach
Parallel.ForEach(myTasks, t => t.DoSomethingInBackground());
Console.Write("All tasks Completed. Now we can do further processing");
You can also perform multiple tasks within a single loop
您还可以在一个循环中执行多个任务
List<string> results = new List<string>(myTasks.Count);
Parallel.ForEach(myTasks, t =>
{
string result = t.DoSomethingInBackground();
lock (results)
{ // lock the list to avoid race conditions
results.Add(result);
}
});
In order for the main UI thread to remain responsive, you will want to use a BackgroundWorker
and subscribe to its DoWork
and RunWorkerCompleted
events and then call
为了使主 UI 线程保持响应,您需要使用 aBackgroundWorker
并订阅其DoWork
和RunWorkerCompleted
事件,然后调用
worker.RunWorkerAsync();
worker.RunWorkerAsync(argument); // argument is an object
回答by Sasidharan
回答by cuongle
You can use Task
library to complete:
您可以使用Task
库来完成:
string[] urls = ...;
var tasks = urls.Select(url => Task.Factory.StartNew(() => DoSomething(url)));
To avoid locking UI Thread, you can use ContinueWhenAll
in .NET 4.0:
为了避免锁定 UI 线程,您可以ContinueWhenAll
在 .NET 4.0 中使用:
Task.Factory.ContinueWhenAll(tasks.ToArray(), _ =>
Console.Write("All tasks Completed. Now we can do further processing");
);
If you are in the latest version of .NET, you can use Task.WhenAll
instead
如果您使用的是最新版本的 .NET,则可以Task.WhenAll
改用
回答by Huy Do
If you use Net 4.0 or up, refer to the Parallel class and Task class. Joseph Albahari wrote very clear book about that: http://www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks
如果您使用 Net 4.0 或更高版本,请参阅 Parallel 类和 Task 类。约瑟夫·阿尔巴哈里 (Joseph Albahari) 对此写了非常清楚的书:http: //www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks