ManagementEventWatcher 通过调用 Stop() 抛出 ManagementException

ManagementEventWatcher throws ManagementException with call to Stop()

我有以下一段代码总是抛出异常:堆栈跟踪如下:

System.Management.ManagementException: Shutting down 
   at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   at System.Management.SinkForEventQuery.Cancel()
   at System.Management.ManagementEventWatcher.Stop()
   at Dell.Client.Framework.Common.RegistryMonitor.StopTreeWatcher()

导致它的代码在 StopTreeWatcher() 中。

private void StopTreeWatcher()
{
    if (bTreeWatcherStarted)
    {
        if (treeChangeWatcher != null)
            treeChangeWatcher.Stop();
        bTreeWatcherStarted = false;
    }
}

private void StartTreeWatcher()
{
    try
    {
        StopTreeWatcher();
        var strQuery = @"SELECT * From RegistryTreeChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND RootPath='" + @regRootPath + "'";
        treeChangeWatcher = new ManagementEventWatcher(new WqlEventQuery(strQuery));
        treeChangeWatcher.Scope.Path.NamespacePath = @"root\default";
        treeChangeWatcher.EventArrived += OnTreeChangeEventArrived;
        treeChangeWatcher.Start();
        bTreeWatcherStarted = true;
     }
     catch (Exception)
     {
        if (throwExceptions)
            throw;
     }
 }

这是因为我没有正确处理 ManagementEventWatcher 对象吗?我不明白 "shutting down" 消息的含义。但是当我启动系统关闭时会发生这种情况。我怎样才能避免这个问题?

如果您在没有 Stop() 或 Dispose() 的情况下调用析构函数,ManagementEventWatcher 将抛出此异常。 我想如果你有 System.Management.ManagementException with errorCode = ShuttingDown (-2147217357),那么你就实现了一个服务。 因此,您必须在您的服务中覆盖 OnShutdown(),您将在其中为您的 ManagementEventWatcher 调用 dispose。如果它不是服务,您必须先捕获有关系统关闭的事件,然后处理您的 ManagementEventWatcher。 您也可以尝试使用此代码来处理 treeChangeWatcher。在多线程应用中使用锁。

private void StopTreeWatcher()
{
    lock (bTreeWatcherStarted)
    {
        if (bTreeWatcherStarted)
        {
            if (treeChangeWatcher != null)
            {
                treeChangeWatcher.EventArrived -= OnTreeChangeEventArrived;
                treeChangeWatcher.Dispose();
                treeChangeWatcher = null;
            }
            bTreeWatcherStarted = false;
        }
    }
}