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

标签 c# multithreading parallel-processing

我是线程编程的新手。我必须在 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并订阅其DoWorkRunWorkerCompleted事件然后调用

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

关于c# - 如何实现多线程并行执行多个任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227430/

相关文章:

c# - 制作游戏 - 安全变量的优势是什么?

c# - 开发 express MVVM : Injected ViewModel is also created by XAML.

c# - Linq 查询中的“System.Data.Entity.Core.EntityCommandExecutionException”

c - 简单 pthread 代码中的奇怪结果

msbuild - 如何在MSBuild中并行运行任务

python - 在 numpy 中加速双循环

linux - 带组捕获的并行 sed

c# - 如何写入 "*.bat"文件?

c++ - 内存排序、指令重新排序和缺少 happens-before 关系

python - Django 非阻塞电子邮件? threading.thread 或子进程的缺点?