使用 System.Diagnostics.PerformanceCounter 类,附加到与您正在索引的驱动器相关的 PhysicalDisk 计数器。
下面是一些用于说明的代码,尽管它目前已硬编码到“C:”驱动器。您需要将“C:”更改为您的进程正在扫描的驱动器。 (这是粗略的示例代码,仅用于说明性能计数器的存在 - 不要将其视为提供准确信息 - 应始终仅用作指导。根据您自己的目的进行更改)
观察 % Idle Time 计数器,该计数器指示驱动器执行任何操作的频率。
0% idle 表示磁盘繁忙,但并不一定表示磁盘已用尽,无法传输更多数据。
将 % Idle Time 与 Current Disk Queue Length 结合起来,这将告诉您驱动器是否变得忙到无法满足所有请求数据。作为一般准则,任何超过 0 的值都意味着驱动器可能完全繁忙,而任何超过 2 的值都意味着驱动器完全饱和。这些规则相当适用于 SSD 和 HDD。
此外,您读取的任何值都是某个时间点的瞬时值。您应该对一些结果进行运行平均,例如在使用结果中的信息做出决定之前每 100 毫秒读取一次读数并平均 5 个读数(即,等到计数器稳定后再发出下一个 IO 请求)。
internal DiskUsageMonitor(string driveName)
{
// Get a list of the counters and look for "C:"
var perfCategory = new PerformanceCounterCategory("PhysicalDisk");
string[] instanceNames = perfCategory.GetInstanceNames();
foreach (string name in instanceNames)
{
if (name.IndexOf("C:") > 0)
{
if (string.IsNullOrEmpty(driveName))
driveName = name;
}
}
_readBytesCounter = new PerformanceCounter("PhysicalDisk",
"Disk Read Bytes/sec",
driveName);
_writeBytesCounter = new PerformanceCounter("PhysicalDisk",
"Disk Write Bytes/sec",
driveName);
_diskQueueCounter = new PerformanceCounter("PhysicalDisk",
"Current Disk Queue Length",
driveName);
_idleCounter = new PerformanceCounter("PhysicalDisk",
"% Idle Time",
driveName);
InitTimer();
}
internal event DiskUsageResultHander DiskUsageResult;
private void InitTimer()
{
StopTimer();
_perfTimer = new Timer(_updateResolutionMillisecs);
_perfTimer.Elapsed += PerfTimerElapsed;
_perfTimer.Start();
}
private void PerfTimerElapsed(object sender, ElapsedEventArgs e)
{
float diskReads = _readBytesCounter.NextValue();
float diskWrites = _writeBytesCounter.NextValue();
float diskQueue = _diskQueueCounter.NextValue();
float idlePercent = _idleCounter.NextValue();
if (idlePercent > 100)
{
idlePercent = 100;
}
if (DiskUsageResult != null)
{
var stats = new DiskUsageStats
{
DriveName = _readBytesCounter.InstanceName,
DiskQueueLength = (int)diskQueue,
ReadBytesPerSec = (int)diskReads,
WriteBytesPerSec = (int)diskWrites,
DiskUsagePercent = 100 - (int)idlePercent
};
DiskUsageResult(stats);
}
}