缓存 Process.Threads 而不是实时值

Cached Process.Threads instead of live value

我无法访问 Process-Object 的线程。

似乎 System.Diagnostics.Process.Threads 是一个缓存数组,而不是在访问时被读取。这意味着,检索另一个应用程序的进程、在应用程序的生命周期中存储它并定期访问它的线程不会产生预期的输出。

一个示例表明,新线程未添加到该列表中。另一个(非托管)进程在此循环期间生成线程:

var cachedProcess = System.Diagnostics.Process.GetProcessesByName("application").FirstOrDefault();
Thread.Sleep(5000); 
while(true)
{
    Console.WriteLine("Cached Thread Count: " + cachedProcess.Threads.Count);

    var liveReadProcess = System.Diagnostics.Process.GetProcessesByName("application").FirstOrDefault();
    Console.WriteLine("Live Thread Count: " + liveReadProcess.Threads.Count);
    Console.WriteLine("");

    Thread.Sleep(1000);
}

输出为:

Cached Thread Count: 3
Live Thread Count: 3

Cached Thread Count: 3
Live Thread Count: 4

Cached Thread Count: 3
Live Thread Count: 5

Cached Thread Count: 3
Live Thread Count: 6

Cached Thread Count: 3
Live Thread Count: 7

我实际上预计 cachedProcess.Threads 上的访问权限等于 liveReadProcess.Threads,但事实并非如此。

有没有办法在不直接访问 WinAPI 的情况下缓存进程句柄并更新线程列表?

Is there a way to cache the process-handle and have an updated Thread-List without accessing the WinAPI directly?

Processclass不会自动更新缓存的线程信息。但是,如果你只是调用Process.Refresh()方法,你可以强制更新:

var cachedProcess = System.Diagnostics.Process.GetProcessesByName("application").FirstOrDefault();
Thread.Sleep(5000); 
while(true)
{
    cachedProcess.Refresh();
    Console.WriteLine("Cached Thread Count: " + cachedProcess.Threads.Count);

    var liveReadProcess = System.Diagnostics.Process.GetProcessesByName("application").FirstOrDefault();
    Console.WriteLine("Live Thread Count: " + liveReadProcess.Threads.Count);
    Console.WriteLine("");

    Thread.Sleep(1000);
}