Process.GetCurrentProcess().Threads 集合中找到当前的processThread

早上和Anakin一起讨论昨天的问题,虽没结果,但从他那里学到了怎么查看线程。
下一步要解决的问题,processThread 和 thread的 区别是什么!

    问题解决了.
    昨天的问题在 Process.GetCurrentProcess().Threads[0].UserProcessorTime 中的Threads[0]是不是当前进程。当然,结果是

不一定。在VS2005的IDE中可以发现当前的thread有11个,Threads[0]不是当前线程。那么关键问题就是怎么获取当前线程。
    processThread类中只有属性ID,而Thread的属性中没有ID只有Name。所以不能通过Thread类的GetCurrentThread来获取当前线

程ID,和processThread联系,只能用其他办法。经查,发现一个系统函数可以获取当前线程ID:

 [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
 
public static extern Int32 GetCurrentWin32ThreadID();

 

    

    当前线程ID获取后,就能在Process.GetCurrentProcess().Threads 集合中找到当前的processThread了。获取函数如下:
       

代码
 class ThreadUtility
    {
        [DllImport(
"Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
        
public static extern Int32 GetCurrentWin32ThreadID();

        
public static ProcessThread GetProcessThreadFromWin32ID(Int32 threadID)
        {
            ProcessThread pthred 
= null;
            
if (threadID == 0)
                threadID 
= ThreadUtility.GetCurrentWin32ThreadID();
         
                
foreach (ProcessThread proThread in Process.GetCurrentProcess().Threads)
                {
                    
if (proThread.Id == threadID)
                        pthred
=proThread;
                    
else
                        pthred
= Process.GetCurrentProcess().Threads[0];
                }
                
return pthred;
        }
    }

 

    这样,问题就解决了。
   
    总结,processThread记录了线程的一些重要信息,比如UserProcessorTime等等。但是peocess没有现成的函数直接找到当前线

程,因此需要用win32系统函数找到当前线程ID后,再在processThread集合中找。

posted @ 2010-05-20 13:46  Jeno  阅读(1901)  评论(0)    收藏  举报