在新线程中启动 Parallel.ForEach 的良好形式

发布于 2024-10-21 19:40:12 字数 546 浏览 1 评论 0 原文

我正在从事一个 Windows 服务项目。该服务启动引擎。该引擎有一对多的“轮询器”,我希望每个轮询器都在自己的线程中运行,以便它们并行地进行“轮询”。我在引擎的 Start() 方法中使用 Parallel.ForEach 来让轮询器进行轮询,效果很好。然而,我希望该服务能够启动引擎,然后继续执行其他操作(例如报告引擎的状态及其在各个点的轮询器或其他内容)。这是在主线程不被阻塞的情况下启动引擎的最佳方法吗:

    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
worker.DoWork += new System.ComponentModel.DoWorkEventHandler((sender, e) => Parallel.ForEach(Pollers.Where(p => p.Active), p => p.StartPolling()));
worker.RunWorkerAsync();

或者有人对更好的方法有任何想法吗?

I am working on a Windows service project. The service starts an engine. The engine has one to many "pollers" that I want to each run in its own thread so that they will do their "polling" in parallel. I am using Parallel.ForEach in the engine's Start() method to get the pollers polling and that's working great. I'd like the service to be able to start the engine, however, and then go on to do other things (like report on the status of the engine and it's pollers at various points or whatever). Is this the best way to start the engine without the primary thread being blocked:

    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
worker.DoWork += new System.ComponentModel.DoWorkEventHandler((sender, e) => Parallel.ForEach(Pollers.Where(p => p.Active), p => p.StartPolling()));
worker.RunWorkerAsync();

Or does anyone have any ideas on a better way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

穿透光 2024-10-28 19:40:12

我会选择 .Net 4 任务库,它比旧的线程模型干净得多,

// Create a task and supply a user delegate by using a lambda expression.
var taskA = new Task(() =>Parallel.ForEach(Pollers.Where(p => p.Active), p =>p.StartPolling()));

// Start the task.
taskA.Start();

您可以阅读有关 任务并行库此处

编辑:您需要包含此命名空间:System.Threading.Tasks

编辑2:是的,正如评论的那样,如果您使用,可能会更好 您应该意识到,

但是

它并不总是最好的方法,根据代码,查看 这个 MSDN 博客 了解有关两者之间差异的更多信息

I'd go with the .Net 4 Task Library, much much cleaner than the old Thread model

// Create a task and supply a user delegate by using a lambda expression.
var taskA = new Task(() =>Parallel.ForEach(Pollers.Where(p => p.Active), p =>p.StartPolling()));

// Start the task.
taskA.Start();

you can Read more about the Task Parallel Library HERE

EDIT: You need to include this namespace: System.Threading.Tasks

EDIT2: Yes, as commented it would probably be better if you use the

Task.Factory.StartNew(() =>{ Parallel.ForEach(Pollers.Where(p => p.Active);})

however you should be aware that it is NOT always the best way, depending on the code, check out THIS MSDN BLOG to read more about the difference between the two

-柠檬树下少年和吉他 2024-10-28 19:40:12

我更喜欢使用Thread,而不是BackgroundWorker。

I would prefer using Thread, rather than BackgroundWorker.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文