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

Aak*_*ash 3 c# parallel-processing multithreading

我是线程编程的新手.我必须在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");
Run Code Online (Sandbox Code Playgroud)

我知道有几种方法可以实现这一目标.但我正在寻找在.Net 4.0(C#)中实现的最佳解决方案.

Nol*_*nar 7

对我来说,这似乎是你想要的 Parallel.ForEach

Parallel.ForEach(myTasks, t => t.DoSomethingInBackground());

Console.Write("All tasks Completed. Now we can do further processing");
Run Code Online (Sandbox Code Playgroud)

您还可以在单​​个循环中执行多个任务

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

worker.RunWorkerAsync();
worker.RunWorkerAsync(argument); // argument is an object
Run Code Online (Sandbox Code Playgroud)