ALL
I was working on a little code which is for search a thread by thread id in the processes of computer.
All my code looks like below , Please help to review it. 🙂
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;
}
}
}
and In another class, I assign a thread to execute my function named DoNothing
ThreadPool.QueueUserWorkItem((t) => Utility.DoNothing((TimeSpan)t),
TimeSpan.FromMinutes(1));
and the function DoNothing code is
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());
}
}
}
}
}
My problem is the Thread.CurrentThread.ManagedThreadId shows 10, I searched it in all the process. But did’t found it .
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.");
}
}
Am I missing something? why I can’t find this thread ? please help me .thanks.
Updated
The original idea of mine to do some experiment with this code is trying to find a way to get the status of the managed thread. obviously in the way I posted here doesn’t make it. so my question is how can I know the status of managed thread with specified thread id? thanks.
Thread.ManagedThreadIdandProcessThread.Idare not comparable. The first is assigned by the .NET runtime, while the second is the value of the native thread handle the OS assigns to each thread.It is also not possible to map one to the other:
Therefore your code cannot be made to work as is.
As an aside, there is a possible race condition here:
It is possible that
proc.Threadsis modified after the array has been initialized but beforeCopyToexecutes. To avoid this race condition evaluateproc.Threadsonly once, for example: