Reputation: 4763
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?
Upvotes: 2
Views: 1459
Reputation: 14594
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
Upvotes: 5