0

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

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 对象吗?我不明白“关闭”消息是什么意思。但是当我启动系统关闭时会发生这种情况。我怎样才能避免这个问题?

4

1 回答 1

2

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

private void StopTreeWatcher()
{
    lock (bTreeWatcherStarted)
    {
        if (bTreeWatcherStarted)
        {
            if (treeChangeWatcher != null)
            {
                treeChangeWatcher.EventArrived -= OnTreeChangeEventArrived;
                treeChangeWatcher.Dispose();
                treeChangeWatcher = null;
            }
            bTreeWatcherStarted = false;
        }
    }
}
于 2018-03-29T08:22:54.233 回答