我正在使用 Visual Studio 2010 来定位 .NET 4.0 客户端配置文件。我有一个 C# 类来检测给定进程何时开始/终止。为此,该类使用一个 ManagementEventWatcher,其初始化如下;query
,scope
和watcher
是类字段:
query = new WqlEventQuery();
query.EventClassName = "__InstanceOperationEvent";
query.WithinInterval = new TimeSpan(0, 0, 1);
query.Condition = "TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'notepad.exe'";
scope = new ManagementScope(@"\\.\root\CIMV2");
watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += WatcherEventArrived;
watcher.Start();
事件 EventArrived 的处理程序如下所示:
private void WatcherEventArrived(object sender, EventArrivedEventArgs e)
{
string eventName;
var mbo = e.NewEvent;
eventName = mbo.ClassPath.ClassName;
mbo.Dispose();
if (eventName.CompareTo("__InstanceCreationEvent") == 0)
{
Console.WriteLine("Started");
}
else if (eventName.CompareTo("__InstanceDeletionEvent") == 0)
{
Console.WriteLine("Terminated");
}
}
此代码基于CodeProject 文章。我添加调用是mbo.Dispose()
因为它泄漏了内存:每次引发 EventArrived 时大约 32 KB,每秒一次。泄漏在 WinXP 和 Win7(64 位)上都很明显。
到现在为止还挺好。为了认真起见,我添加了一个try-finally
子句,如下所示:
var mbo = e.NewEvent;
try
{
eventName = mbo.ClassPath.ClassName;
}
finally
{
mbo.Dispose();
}
那里没问题。更好的是,C#using
子句更紧凑但等效:
using (var mbo = e.NewEvent)
{
eventName = mbo.ClassPath.ClassName;
}
太好了,只是现在内存泄漏又回来了。发生了什么?
嗯,我不知道。但是我尝试用 ILDASM 拆解这两个版本,它们几乎但不完全相同。
来自try-finally
:
.try
{
IL_0030: nop
IL_0031: ldloc.s mbo
IL_0033: callvirt instance class [System.Management]System.Management.ManagementPath [System.Management]System.Management.ManagementBaseObject::get_ClassPath()
IL_0038: callvirt instance string [System.Management]System.Management.ManagementPath::get_ClassName()
IL_003d: stloc.3
IL_003e: nop
IL_003f: leave.s IL_004f
} // end .try
finally
{
IL_0041: nop
IL_0042: ldloc.s mbo
IL_0044: callvirt instance void [System.Management]System.Management.ManagementBaseObject::Dispose()
IL_0049: nop
IL_004a: ldnull
IL_004b: stloc.s mbo
IL_004d: nop
IL_004e: endfinally
} // end handler
IL_004f: nop
来自using
:
.try
{
IL_002d: ldloc.2
IL_002e: callvirt instance class [System.Management]System.Management.ManagementPath [System.Management]System.Management.ManagementBaseObject::get_ClassPath()
IL_0033: callvirt instance string [System.Management]System.Management.ManagementPath::get_ClassName()
IL_0038: stloc.1
IL_0039: leave.s IL_0045
} // end .try
finally
{
IL_003b: ldloc.2
IL_003c: brfalse.s IL_0044
IL_003e: ldloc.2
IL_003f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0044: endfinally
} // end handler
IL_0045: ldloc.1
显然问题是这一行:
IL_003c: brfalse.s IL_0044
这相当于if (mbo != null)
,所以mbo.Dispose()
永远不会被调用。但是,如果 mbo 能够访问,它怎么可能为 null.ClassPath.ClassName
呢?
对此有什么想法吗?
另外,我想知道这种行为是否有助于解释此处未解决的讨论:Memory leak in WMI when querying event logs。