C# How to count managed threads in my AppDomain?

梦想与她 提交于 2019-12-09 16:14:12

问题


Is there a way to find out how many managed thread I use (including ThreadPool)?

When I get count of unmanaged threads through GetProcess I have an insane number of it (21 at very beginning)


回答1:


That's not the way it works. Any thread in a managed program can execute managed code, including ones that were originally started as an unmanaged thread. Which most are, the main thread and any threadpool thread starts life executing purely unmanaged code. It thunks into managed code though the kind of gateway provided by Marshal.GetDelegateForFunctionPointer().

Seeing dozens of (otherwise inactive) threads is not unusual. They typically are threadpool threads and threads started by COM servers. .NET is missing the plumbing you'd need to use Thread.ManagedThreadId on those threads. That's intentional, a logical .NET thread doesn't have to be a physical operating system thread. Although there's no host in current use where that's not the case.

You will have to avoid having to ask the question.




回答2:


I have not checked whether it is possible using the debugging interfaces but since VS displays managed threads in its debugger, you should be able to get them in yours too.

In .NET, writing a debugger is much easier than you may expect. Implementing the debugger basically consists of implementing the ICorDebug interface.

There is a sample from Microsoft: Managed Debugger Sample



来源:https://stackoverflow.com/questions/3068813/c-sharp-how-to-count-managed-threads-in-my-appdomain

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