10

我们会定期在无法重现的生产环境中关闭 Windows 服务。可能需要几个月的时间才能再次发生。

我正在进行一些诊断以尝试帮助解决该问题,我正在查看的一件事是在我们启动关闭应用程序后将事件添加到系统线程池 60 秒。我们的应用程序应该在最多 10 秒内完全关闭。

在这种情况下,我想将进程的剩余运行线程追踪到事件日志。

我可以使用 System.Diagnostics.Process.GetCurrentProcess.Threads 获取正在运行的线程。这些线程对象具有本机 Win32 线程 ID 等。

我想知道是否有任何方法可以从这些线程 ID 返回到它们在当前进程中代表的任何托管线程。我尝试这样做的原因是因为对于我们的线程池和我们生成的其他线程,我们给出了代表它们的目的的名称,这真的有助于取回这些名称。

4

2 回答 2

12

This is impossible for the following reason. Quote from MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

So there's no one-to-one mapping between managed threads and OS threads.

So now the question becomes, how to get a list of all the managed threads currently running in the current process? Unfortunately I don't know the answer.

于 2009-11-17T15:59:20.710 回答
0

看起来这不可能。
对我们来说幸运的是,我们有自己的线程库来包装 .NET 库,并且我能够添加功能来保留可用于这些诊断的活动线程列表。
这工作得很好,但当然需要付出相当多的努力和测试,但希望我们能深入了解它。

于 2009-11-19T10:20:52.493 回答