对我来说,vstesthost的实例名往往是一个长字符串,看起来与guid后面跟着pid有点类似,因此计算实例名有点麻烦,不过如果您知道pid(我马上就会知道),那么可以通过以下几行操作来完成:
PerformanceCounterCategory category = new PerformanceCounterCategory(
".NET Data Provider for SqlServer");
string testInstanceName = null;
foreach(string instanceName in category.GetInstanceNames())
{
if (instanceName.EndsWith(string.Format("[{0}]", pid)))
{
testInstanceName = instanceName;
break;
}
}
if(testInstanceName != null)
{
PerformanceCounter counter = new PerformanceCounter(
category.CategoryName,
"Number of Active Connections",
testInstanceName,
true);
}
由于在单元测试期间调用getEntryassembly()返回空值,因此获取vstesthost.exe的PID也是一种痛苦。但是,您应该能够沿着这些线做一些事情:
Process[] testProcesses = Process.GetProcessesByName("VSTestHost");
if (testProcesses.Length == 1)
{
pid = testProcesses[0].Id;
}