我有以下代码总是抛出异常: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 = @"root\default";
treeChangeWatcher.EventArrived += OnTreeChangeEventArrived;
treeChangeWatcher.Start();
bTreeWatcherStarted = true;
}
catch (Exception)
{
if (throwExceptions)
throw;
}
}
这是因为我没有正确处理ManagementEventWatcher对象吗?我不明白"关闭"消息意味着但是当我启动系统关闭时会发生这种情况。我该如何避免这个问题?
答案 0 :(得分: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;
}
}
}