我正在从事一个 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?
发布评论
评论(2)
我会选择 .Net 4 任务库,它比旧的线程模型干净得多,
您可以阅读有关 任务并行库此处
编辑:您需要包含此命名空间:
System.Threading.Tasks
编辑2:是的,正如评论的那样,如果您使用,可能会更好 您应该意识到,
但是
它并不总是最好的方法,根据代码,查看 这个 MSDN 博客 了解有关两者之间差异的更多信息
I'd go with the .Net 4 Task Library, much much cleaner than the old Thread model
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
我更喜欢使用Thread,而不是BackgroundWorker。
I would prefer using Thread, rather than BackgroundWorker.