views:

168

answers:

3

How do I find the processor on which my thread is running in C#?

+1  A: 

IMHO it's possible that the .NET thread is not bound to any of the native threads. >NET runtime can move the .NET threads between different native threads and processors anytime.

Vlad
This was attempted, but abandoned. There is no CLR version currently where a Thread doesn't match an operating system thread. Given the drastic failure to make it work with fibers (a SQL Server team project), this is unlikely to change any time soon.
Hans Passant
+4  A: 

This is not necessarily a constant - the thread could be scheduled onto different cores across its lifetime. You can set affinity masks to tie a particular thread to a particular CPU if you want to. See the API docs for Thread.BeginThreadAffinity for more details on what can be done within .Net.

ConcernedOfTunbridgeWells
+1  A: 

I'm not sure that you can. You can get the process affinity mask (GetProcessAffinityMask), and set the same (SetProcessAffinityMask). You can also set the thread affinity mask, but my understanding is that in doing so you restrict the thread to running on one of the processors you've set your affinity mask to.

If you're delving into specific threads running on specific cores you probably want to set the process affinity mask to define the set of cores your code can run on, and the threads in your process will then float among the selected cores.

Andrew