简体   繁体   中英

ManagementEventWatcher throws ManagementException with call to Stop()

I have the following piece of code that always throws an exception: The stacktrace is as follows:

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()

The code that is causing it is in 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;
     }
 }

Is this because I am not disposing the ManagementEventWatcher object properly? I don't understand what the "shutting down" message means. But this happens when I initiate a system shutdown. How can I avoid this issue?

The ManagementEventWatcher throws this exception if you call the destructor without Stop() or Dispose(). I suppose that if you have the System.Management.ManagementException with errorCode = ShuttingDown (-2147217357), then you implement a service. So you have to override OnShutdown() in you service, in which you will call dispose for your ManagementEventWatcher. If it is not a service, you have to catch event about system shutdown firstly and then dispose your ManagementEventWatcher. You can also try this code for disposing the treeChangeWatcher. Use lock in multithreaded app.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM