ManagementEventWatcher通过Call to stop()抛出ManagementException



我有以下代码,总是会引发异常:stacktrace如下:

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 = @"rootdefault";
        treeChangeWatcher.EventArrived += OnTreeChangeEventArrived;
        treeChangeWatcher.Start();
        bTreeWatcherStarted = true;
     }
     catch (Exception)
     {
        if (throwExceptions)
            throw;
     }
 }

这是因为我没有正确处理ManagementEventWatcher对象吗?我不明白"关闭"消息的含义。但是,当我启动系统关闭时,就会发生这种情况。我如何避免此问题?

如果您无需停止()或dispose()调用destructor,则管理EventWatcher会抛出此异常。我想,如果您的system.management.managementException带有errorCode = shuttingdown(-2147217357),则可以实现服务。因此,您必须在服务中覆盖onshutdown(),在其中您将为您的ManagementEventWatcher拨打Dispose。如果不是服务,则必须首先捕获有关系统关闭的事件,然后处理您的ManagementEventWatcher。您也可以尝试此代码以处置TreachangeWatcher。在多线程应用中使用锁。

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

相关内容

  • 没有找到相关文章

最新更新