如何实现多线程并并行执行多个任务
本文关键字:并行执行 任务 多线程 何实现 实现 | 更新日期: 2023-09-27 18:27:33
我是线程编程的新手。我必须在PARALLEL和Background中运行一些任务(以便主UI执行线程对用户操作保持响应),并等待每个任务完成后再继续执行。
类似于:
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");
我知道有几种方法可以实现这一点。但我正在寻找在.Net 4.0(C#)中实现的最佳解决方案。
对我来说,你似乎想要Parallel.ForEach
Parallel.ForEach(myTasks, t => t.DoSomethingInBackground());
Console.Write("All tasks Completed. Now we can do further processing");
您还可以在单个循环中执行多个任务
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);
}
});
为了使主UI线程保持响应,您需要使用BackgroundWorker
并订阅其DoWork
和RunWorkerCompleted
事件,然后调用
worker.RunWorkerAsync();
worker.RunWorkerAsync(argument); // argument is an object
您可以使用Task
库来完成:
string[] urls = ...;
var tasks = urls.Select(url => Task.Factory.StartNew(() => DoSomething(url)));
为了避免锁定UI线程,可以在.NET 4.0:中使用ContinueWhenAll
Task.Factory.ContinueWhenAll(tasks.ToArray(), _ =>
Console.Write("All tasks Completed. Now we can do further processing");
);
如果您使用的是最新版本的.NET,则可以使用Task.WhenAll
而不是
如果使用Net 4.0或更高版本,请参阅Parallel类和Task类。Joseph Albahari写了一本非常明确的书:http://www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks