为什么我在Asp.Net Framewok线程池中找不到指定的线程

Joe*_*ang 0 .net c# multithreading threadpool

所有

我正在研究一个小代码,用于在计算机进程中通过线程id搜索线程.

我的所有代码如下所示,请帮助查看.:)

    using System.Diagnostics;

    public class NKDiagnostics
    {
        private Process[] m_arrSysProcesses;

        private void Init()
        {
            m_arrSysProcesses = Process.GetProcesses(".");
        }
        public static ProcessThread[] GetProcessThreads(int nProcID)
        {
            try
            {
                Process proc = Process.GetProcessById(nProcID);
                ProcessThread[] threads = new ProcessThread[proc.Threads.Count];
                proc.Threads.CopyTo(threads, 0);
                return threads;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在另一个类中,我指定一个线程来执行我的名为的函数 DoNothing

    ThreadPool.QueueUserWorkItem((t) => Utility.DoNothing((TimeSpan)t), 
TimeSpan.FromMinutes(1));
Run Code Online (Sandbox Code Playgroud)

而功能DoNothing代码是

public class Utility
    {
        public static void DoNothing(TimeSpan timeout, TextBox txtThreadId)
        {
            TimeoutHelper helper = new TimeoutHelper(timeout);
            while (true)
            {
                Thread.Sleep(1000 * 5);
                if (helper.RemainingTime() <= TimeSpan.Zero)
                {
                    MessageBox.Show("This thread's work is finished.");
                    break;
                }
                else
                {

                    if (Thread.CurrentThread.IsThreadPoolThread)
                    {
                        MessageBox.show( Thread.CurrentThread.ManagedThreadId.ToString());
                    }

                }
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是Thread.CurrentThread.ManagedThreadId节目10,我在所有过程中搜索了它.但是没找到它.

ProcessThread[] m_Threads = NKDiagnostics.GetProcessThreads(processId);
for (int i = 0; i < m_Threads.Length; i++)
            {

                if (m_Threads[i].Id.Equals(10))
                {
                    MessageBox.Show("Found it.");
                }
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?为什么我找不到这个帖子?请帮助我.谢谢.

更新

我最初对这段代码进行实验的想法是试图找到一种获取托管线程状态的方法.显然我在这里发布的方式并没有成功.所以我的问题是如何知道具有指定线程ID的托管线程的状态?谢谢.

Jon*_*Jon 5

Thread.ManagedThreadIdProcessThread.Id没有可比性.第一个是由.NET运行时分配的,而第二个是OS分配给每个线程的本机线程句柄的值.

不可能将一个映射到另一个:

操作系统ThreadId与托管线程没有固定的关系,因为非托管主机可以控制托管和非托管线程之间的关系.具体而言,复杂的主机可以使用Fiber API针对同一操作系统线程调度许多托管线程,或者在不同的操作系统线程之间移动托管线程.

因此,您的代码无法按原样运行.

顺便说一句,这里可能存在竞争条件:

ProcessThread[] threads = new ProcessThread[proc.Threads.Count];
proc.Threads.CopyTo(threads, 0);
Run Code Online (Sandbox Code Playgroud)

可能proc.Threads在数组初始化之后但在CopyTo执行之前进行了修改.为了避免这种竞争条件,proc.Threads只评估一次,例如:

var threads = proc.Threads.ToArray();
Run Code Online (Sandbox Code Playgroud)