Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force C# application to use a single core in a PC with a multicore processor

I am using the Haptek People Putty player for my C# application and I've seen people say in the forums that it doesn't work well with a multicore processor. My application runs well on my Core 2 Duo laptop but it lags a lot when I try running it on a Quad Core desktop. I was thinking of investigating this for myself and in that case, I would have to force my application to run on a single core. Is that possible in C#?

like image 852
Paul Avatar asked Aug 07 '10 09:08

Paul


2 Answers

Where a Process variable proc holds the process you care about (Process.GetCurrentProcess() for the running Process, obtaining it from GetProcesses() or GetProcessesByName() etc. for another process. Then:

foreach(ProcessThread pt in proc.Threads)
{
   pt.IdealProcessor = 0;
   pt.ProcessorAffinity = (IntPtr)1;
}

IdealProcessor is a zero-based identity of a single core. ProcessorAffinity is a bitmask, so 1 allows core zero, 2 allows core one, 3 allows cores zero and one, 4 allows core two, and so on.

I would test this thoroughly. Chances are very strong that this will actually damage your performance, in reducing the ability to make use of different cores, which is after-all generally an advantage.

like image 114
Jon Hanna Avatar answered Oct 05 '22 18:10

Jon Hanna


If the application is single-threaded, it will not take advantage of multiple cores. However, it is possible that the kernel can bump the thread around between cores. I doubt that this is the cause of your performance problems.

If you would like to tie the thread down to a single core (not sure if this can be guaranteed), you might want to check out the System.Diagnostics.ProcessThread.ProcessorAffinity property, although I have never used it myself.

like image 44
Ani Avatar answered Oct 05 '22 18:10

Ani