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了。获取函数如下:
       

ExpandedBlockStart.gif 代码
  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集合中找。

转载于:https://www.cnblogs.com/plaqin/archive/2010/05/20/1739995.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值