开发者

How often does a managed thread switch OS threads?

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

If the CLR may switch a managed thread between OS threads, how often does this happen? What influence the frequency?

I've got a separate question on how to stop the switching from happening. Second prize for me would be for this to not happen too often (less than once a minute开发者_如何学运维 would be fine).


It completely depends on the host. There is no guarantee as to when or where a thread switch might take place (if at all), given any particular host.

However, since .NET 2.0, you have been able to call the static BeginThreadAffinity method to notify the host that the code that is running depends on the identity of the underlying 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 done (I'm not sure what happens if you just let the thread end without calling EndThreadAffinity. I can't imagine it would have an impact, but it's better to be explicit in this matter, IMO):

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


As far as I am aware the current implementation of the CLR maps managed threads to OS threads. However, as the documentation says this is not guaranteed, i.e. it is an implementation detail so you can't assume anything. It could change, but even if it doesn't the advice of the documentation is that you shouldn't rely on a one to one mapping.

As casperOne points out you can set thread affinity but apart from that, there are no guarantees.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜