我正在使用此類作爲啓動進程並給它一些輸入並等待它變爲空閒的測試類別的基類然後再給它更多的投入。即使進程沒有退出,進程的性能計數器實例名稱是否可以更改
public abstract class TestProcessLaunchingBase
{
protected PerformanceCounter PerfCounter { get; set; }
protected void WaitForProcessIdle()
{
while (true)
{
float oldValue = PerfCounter.NextValue();
Thread.Sleep(1000);
float nextValue = PerfCounter.NextValue();
if (nextValue == 0)
break;
}
}
protected void FindSpawnedProcessPerfCounter(int processId)
{
PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
string[] instances = cat.GetInstanceNames();
foreach (string instance in instances)
{
using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true))
{
int val = (int)cnt.RawValue;
if (val == processId)
{
PerfCounter = new PerformanceCounter("Process", "% Processor Time", instance);
break;
}
}
}
Assert.IsNotNull(PerfCounter, "Failed to perf counter");
}
}
這些測試偶爾會失敗,因爲PerfCounter.NextValue()
拋出
System.InvalidOperationException 實例 'foobar的#2' 中指定的類別
好像實例名稱不存在的性能計數器不是持久的。
如果有三個foobar的過程中,他們可能有實例名稱
- foobar的 PID 5331
- foobar的#1 PID 5332
- foobar的#2 PID 5333
好像是pid 5332 exits foobar#2變成foobar#1。
問題:
這是一個記錄的行爲?你不能堅持一個表現計數器嗎?你每次都必須查看它嗎?
另外,有可以給處理器時間名爲foobar的
P/Invoke:'GetProcessTimes'給出給定進程的用戶和內核模式時間。我們需要先用'OpenProcess'獲得進程句柄,如果這個應用程序的另一個實例關閉,它肯定不會改變。 – 2012-08-13 17:43:17