i have a windows service written in .net 4 which doing jobs periodically using Threads. the server has more than 20 cpu core.
i create 10 threads in my windows service.
It is possible by tapping into the native Win32 system calls, specifically SetThreadAffinityMask. You will need to do some DllImports:
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
And then use them inside each spawned thread (with a different parameter for the mask, of course):
// set affinity of current thread to the given cpuID
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1 << (int)cpuID));
Warning: Direct correlation between .NET threads and OS threads is not guaranteed, at least according to this: http://msdn.microsoft.com/en-us/library/74169f59.aspx
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the Fiber API to schedule many managed threads against the same operating system thread, or to move a managed thread among different operating system threads.