How often is a managed thread switching OS threads to OS?

I understand that managed threads are not guaranteed to work on the same OS thread.

If the CLR can switch a managed thread between OS threads, how often does this happen? What is the effect on frequency?

I have a separate question on how to stop the switch. The second prize for me would not be too often for this (less than once a minute would be good).

+5
multithreading clr
Dec 30 '09 at 9:15
source share
2 answers

It is completely up to the host. There is no guarantee as to when or where a thread switch may occur (if at all), given any particular host.

However, starting with .NET 2.0, you can call the static BeginThreadAffinity method to notify the host that the code being executed depends on the identity of the main OS thread:

http://msdn.microsoft.com/en-us/library/system.threading.thread.beginthreadaffinity(VS.80).aspx

Of course, make sure you call the EndThreadAffinity method when your thread is finished (I’m not sure what will happen if you just allow the thread to end without calling EndThreadAffinity. I can’t imagine this to have an effect, but it’s better to be explicit in this question. IMO):

http://msdn.microsoft.com/en-us/library/system.threading.thread.endthreadaffinity(VS.80).aspx

+7
Dec 30 '09 at 9:24
source share

To my knowledge, the current CLR implementation maps managed threads to OS threads. However, as the documentation says, this is not guaranteed, i.e. This is an implementation detail, so you cannot accept anything. This may change, but even if it is not a recommendation of the documentation, you should not rely on a one-to-one mapping.

As casperOne points out, you can establish thread affinity, but there is no guarantee beyond that.

+4
Dec 30 '09 at 9:24
source share



All Articles