【发布时间】:2012-08-09 14:36:58
【问题描述】:
我使用这个类作为一类测试的基类,这些测试启动一个进程并给它一些输入,然后等待它变得空闲,然后再给它更多输入。
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 退出 foobar #2 似乎变成 foobar #1。
问题:
这是记录在案的行为吗?你不能坚持一个性能计数器吗?每次都要查吗?
或者,是否有一个性能计数器可以为所有名为 foobar
的进程提供 Processor Time
【问题讨论】:
标签: c#