【发布时间】:2011-01-04 13:36:22
【问题描述】:
我想从我的应用程序中获取一个包含所有线程(主、GUI 线程除外)的列表,以便对它们执行一些操作。 (设置优先级,杀死,暂停等) 怎么做?
【问题讨论】:
标签: windows delphi multithreading process
我想从我的应用程序中获取一个包含所有线程(主、GUI 线程除外)的列表,以便对它们执行一些操作。 (设置优先级,杀死,暂停等) 怎么做?
【问题讨论】:
标签: windows delphi multithreading process
另一个选项是使用CreateToolhelp32Snapshot、Thread32First 和Thread32Next 函数。
查看这个非常简单的示例(在 Delphi 7 和 Windows 7 中测试)。
program ListthreadsofProcess;
{$APPTYPE CONSOLE}
uses
PsAPI,
TlHelp32,
Windows,
SysUtils;
function GetTthreadsList(PID:Cardinal): Boolean;
var
SnapProcHandle: THandle;
NextProc : Boolean;
TThreadEntry : TThreadEntry32;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
if Result 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
begin
Writeln('Thread ID '+inttohex(TThreadEntry.th32ThreadID,8));
Writeln('base priority '+inttostr(TThreadEntry.tpBasePri));
Writeln('');
end;
NextProc := Thread32Next(SnapProcHandle, TThreadEntry);//get the Next Thread
end;
finally
CloseHandle(SnapProcHandle);//Close the Handle
end;
end;
begin
{ TODO -oUser -cConsole Main : Insert code here }
GettthreadsList(GetCurrentProcessId); //get the PID of the current application
//GettthreadsList(5928);
Readln;
end.
【讨论】:
你可以使用我的TProcessInfo类:
var
CurrentProcess : TProcessItem;
Thread : TThreadItem;
begin
CurrentProcess := ProcessInfo1.RunningProcesses.FindByID(GetCurrentProcessId);
for Thread in CurrentProcess.Threads do
Memo1.Lines.Add(Thread.ToString);
end;
【讨论】:
如果它们是您的线程,那么我将创建一个应用程序全局线程管理器,以便在创建时向其注册。然后,您就可以使用线程管理器正常地监控、暂停和关闭线程了。
【讨论】:
您可以使用 WMI 访问此信息。
WIN32_Process 可以为您提供有关在机器上执行的进程的所有信息。对于每个进程,你可以给 ThreadsCount, Handle,...
另一个类,WIN32_Thread 可以为您提供有关机器上运行的所有线程的详细信息。这个类有一个名为 ProcessId 的属性,用于搜索 1 个进程的特定线程(类 WIN32_Process)。
为了测试它,你可以在命令行窗口上执行它:
// all processes
WMIC PROCESS
// information about Delphi32
WMIC PROCESS WHERE Name="delphi32.exe"
// some information about Delphi32
WMIC PROCESS WHERE Name="delphi32.exe" GET Name,descrption,threadcount,Handle
(NOTE: The handle for delphi32.exe in my machine is **3680**)
您可以使用进程的句柄对 WIN32_Thread 执行类似的操作。
对不起,我的英语不好。
问候。
【讨论】: