我正在使用delphi 2010,是否有通过delphi函数或Windows API知道项目运行线程数的信息?

最佳答案

您可以将 CreateToolhelp32Snapshot 函数与TH32CS_SNAPTHREAD标志一起使用

看到这个代码。

  uses
  PsAPI,
  TlHelp32,
  Windows,
  SysUtils;

    function GetTThreadsCount(PID:Cardinal): Integer;
    var
        SnapProcHandle: THandle;
        NextProc      : Boolean;
        TThreadEntry  : TThreadEntry32;
        Proceed       : Boolean;
    begin
        Result:=0;
        SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
        Proceed := (SnapProcHandle <> INVALID_HANDLE_VALUE);
        if Proceed then
          try
            TThreadEntry.dwSize := SizeOf(TThreadEntry);
            NextProc := Thread32First(SnapProcHandle, TThreadEntry);//get the first Thread
            while NextProc do
            begin
              if TThreadEntry.th32OwnerProcessID = PID then //Check the owner Pid against the PID requested
              Inc(Result);
              NextProc := Thread32Next(SnapProcHandle, TThreadEntry);//get the Next Thread
            end;
          finally
            CloseHandle(SnapProcHandle);//Close the Handle
          end;
    end;

然后使用 GetCurrentProcessId 函数以这种方式调用,该函数将检索应用程序的PID(进程标识符)。
Var
Num :integer;
begin
 Num:=GetTThreadsCount(GetCurrentProcessId);
end;

关于multithreading - 运行线程数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3809708/

10-11 21:05