I need to allocate a workload on different processes, depending on the number of logical cores of the user’s PC.
The workload is done by the following code :
static void work()
{
WorkData myData = new WorkData();
Worker myWorker = new Worker(myData);
MyWorker.doWork()
}
I count the logical cores with this code :
int nbProcessors = 1;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
nbProcessors = Convert.ToInt32(item["NumberOfLogicalProcessors"]);
}
Now, I have to do my work() 10000 times, by sharing the work on the logical cores, so in the case of my pc it would mean starting 8 processes with 1250 iterations of work() each.
I also need each process to have its own data, so that I don’t get conflicts.
How can I do that?
I think you should review Parallel methods and ThreadPool methods.
Both of this classes are counting on current workstation configuration, so you can easily use them for your task.
Example of Parrallel usage:
Parallel Loops:
Thread Pool task-oriented example:
Update from comments:
Task Parallel Library (Parralel class) internally uses Threading.Tasks namespace, with some process managing:
Two another links about: Task Parallelism and Data Parallelism. I think second link can help you with balancing the work for your data.