如何实现multithreading并行执行多个任务?

我是线程编程的新手。 我必须在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 results = new List(myTasks.Count); Parallel.ForEach(myTasks, t => { string result = t.DoSomethingInBackground(); lock (results) { // lock the list to avoid race conditions results.Add(result); } }); 

为了使主UI线程保持响应,您将需要使用BackgroundWorker并订阅其DoWorkRunWorkerCompleted事件,然后调用

 worker.RunWorkerAsync(); worker.RunWorkerAsync(argument); // argument is an object 

检查以下链接

.net 4.0multithreading并行编程

您可以使用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