缓存Process.Threads而不是实时值

时间:2015-06-03 22:20:53

标签: c# multithreading process

我无法访问Process - 对象的线程。

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

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

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,但事实并非如此。

有没有办法缓存进程句柄并拥有更新的Thread-List而无需直接访问WinAPI?

1 个答案:

答案 0 :(得分:2)

  

有没有办法缓存进程句柄并拥有更新的Thread-List而无需直接访问WinAPI?

Process类不会自动更新缓存的线程信息。但是,如果您只是调用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);
}