How often does a managed thread switch OS threads?

六眼飞鱼酱① 提交于 2019-12-07 04:14:08

问题


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).


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1979210/how-often-does-a-managed-thread-switch-os-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!