How often does a managed thread switch OS threads?

╄→гoц情女王★ 提交于 2019-12-05 10:17:07

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.

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