我是线程编程的新手。我必须在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
andRunWorkerCompleted
事件,然后调用
worker.RunWorkerAsync();
worker.RunWorkerAsync(argument); // argument is an object
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句