我是线程编程的新手。我必须在 PARALLEL 和后台运行几个任务(以便主 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
关于c# - 如何实现多线程并行执行多个任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227430/