ManagementEventWatcher内存泄漏问题

本文关键字:问题 泄漏 内存 ManagementEventWatcher | 更新日期: 2023-09-27 18:16:17

我可能使用术语内存泄漏不好,但我不确定有任何其他方式来描述它。我已经编写了一个Windows Service,它使用managementteventwatcher类来监视特定实例的启动。一旦它看到这个实例,它就启动另一个实例作为响应。我已经成功地在多台计算机上测试了这项服务,并取得了全面的成功。

我遇到的问题是,当服务启动时,它平均使用2400k。但是,如果让服务运行一夜,我发现在早上任务管理器中的进程占用了12000k的私有工作内存。

这使我相信某物不是在处理事件,但我无法辨别是什么。

我认为这可能与事件到达行有关:观察者。EventArrived += new EventArrivedEventHandler…

我相信这是因为它需要使用add赋值操作符。我想测试这个理论,但我有麻烦辨别我应该把减号赋值操作符。是否会在第一行之后直接清除一行以防止合用?或者有人发现了我遗漏的明显的清理方法吗?附加的是服务调用的代码:

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;
    }

}

ManagementEventWatcher内存泄漏问题

我们在使用ManagementEventWatcher后也遇到了同样的问题,除了更极端的情况,由于我们经常触发WMI事件,内存使用量飙升到几gb范围。

事实证明,解决方案是,在EventArrived事件中,您需要在e.NewEvent上手动调用Dispose()。您错过了相同的清理。