我可能对“内存泄漏”这个词的使用不好,但我不确定是否有任何其他方式来描述它。我编写了一个 Windows 服务,它使用 ManagementEventWatcher 类来监视特定实例的启动。一旦它看到该实例,它就会启动另一个作为响应。我已经成功地在多台计算机上成功地测试了这项服务,并且全面成功。
我遇到的问题是,当服务启动时,它平均使用 2400k。然而,让服务在一夜之间运行,我在早上发现该进程在任务管理器中位于 12000k 的私有工作内存中。
这使我相信某事并没有处理事件,但我无法辨别是什么。
我相信这可能与事件到达线有关: watcher.EventArrived += new EventArrivedEventHandler...
我相信这是因为它需要使用添加赋值运算符。我想测试这个理论,但我无法辨别将减号赋值运算符放在哪里。是否会在第一行之后直接清除该行以防止池化?或者有没有人看到我遗漏的任何明显的清理方法?附上服务调用的代码:
class Monitor
{
//Pulls process watching and launch path as well as args from xml config file.
private static string procWatch = ConfigurationManager.AppSettings["watchFor"];
private static string filePath = ConfigurationManager.AppSettings["filePath"];
private static string filePath2 = ConfigurationManager.AppSettings["filePath2"];
public static ManagementEventWatcher watchforProcess()
{
//Creates ManagementEventWatcher Object to return to the service.
ManagementScope scope = new ManagementScope(@"\\.\root\CIMV2");
WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
return watcher;
}
public static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
//Event handler that launches a process if it's name matches proc watch
string instanceName = ((ManagementBaseObject)e.NewEvent["TargetInstance"])["Name"].ToString();
if (instanceName.ToLower() == procWatch)
{
EventLog.WriteEntry("KaceWatcher", "Kace process found.");
Process.Start(filePath, filePath2);
}
//Should I place a null here to clear up each instanceName.
}
public static void finalize()
{
//Used for service stop
procWatch = null;
filePath = null;
filePath2 = null;
}
}