Reputation: 335
I have a python script that I would like to rewrite in C# that makes use of multiprocessing. I have been reading about C# multithreading and multiprocessing and I am thoroughly confused. Many of the articles suggest using TPL or something like Parrallel.Foreach but many of the pages start by mentioning multiple cores then quickly switch back to talking about threads. In Python I had to specifically use the multiprocessing module to achieve this (see: Multiprocessing vs Threading Python )
I wrote a small sample console app to test:
class Program
{
static void Main(string[] args)
{
List<int> testList = new List<int>();
testList.AddRange(Enumerable.Range(1, 20));
Parallel.ForEach(testList, x => Console.WriteLine(Test(x)));
Console.ReadLine();
}
private static string Test(int i)
{
Thread.Sleep(1000 * (21 - i));
return "P: " + Process.GetCurrentProcess().Id.ToString() + ", T: " + Thread.CurrentThread.ManagedThreadId.ToString();
}
}
However, it shows one process ID and multiple thread IDs. Now I am not sure if my method is correct and if I am understanding everything correctly.
To give a bit of background my application requires a lot of computation on small amounts of datasets (+-300 data points), but due to a huge combination of parameters, I need these to run as fast as possible to save time.
Basically what I want to know is if Parallel.Foreach threads will automatically run on different cores or is there something else I need to do.
Upvotes: 3
Views: 6945
Reputation: 111870
The Microsoft .NET runtime maps .NET threads to Windows threads 1:1 (so each .NET thread is a Windows OS thread). Different Windows threads are normally scheduled by the Windows scheduler to different CPU cores. So you don't have to do anything.
As always remember that threads are "expensive" objects. Unless you can have "much" work for each thread, it is useless to use them (don't use threads for unit of work < 1 sec, unless you have very specific necessities)
Upvotes: 3