gpt4 book ai didi

c# - ManagementEventWatcher - 应用程序退出时出现 InvalidObjectException

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:13 25 4
gpt4 key购买 nike

我已经构建了一个使用 ManagementEventWatcher 类的 .net 库。我的库是一次性的,所以通常我会把它包装在一个 using 语句中,ManagementEventWatcher 类会被我的库处理掉。

我的问题是我的库暴露给 COM,并在不使用一次性模式的 VB6 中使用。如果用户不从他们的 .net 应用程序中调用库上的处置,或者不能因为 VB6,ManagementEventWatcher 类将从 中抛出一个 InvalidComObjectException >SinkForEventQuery.Cancel

我无法捕获异常,所以它仍未处理,这是不好的。我可以尝试一些解决方法吗?

System.Runtime.InteropServices.InvalidComObjectException was unhandled
Message=COM object that has been separated from its underlying RCW cannot be used.
Source=mscorlib
StackTrace:
at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis, IntPtr pThread)
at System.Management.IWbemServices.CancelAsyncCall_(IWbemObjectSink pSink)
at System.Management.SinkForEventQuery.Cancel()
at System.Management.ManagementEventWatcher.Stop()
at System.Management.ManagementEventWatcher.Finalize()
InnerException:

最佳答案

我今天遇到了同样的问题,基本上我无法在类上调用 dispose 并且 WMI 对象没有被释放,给了我同样的错误。

我最后所做的是实现一个不同的接口(interface)而不是 IDisposable,公开两个方法:Init 和 TearDown,并使用这些方法来设置我的 MEW 并处理它。不过这有点 hack,如果类的用户不知道这一点,他将永远不会调用这两个方法,并且您的 MEW 将永远不会启动或被处置。

另一种方法可能是让类连接到诸如“OnDestroy”之类的事件,并通过拆除 MEW 对象做出相应的响应。

    public void Init()
{
if (mew == null)
{
mew = new ManagementEventWatcher(query);
mew.EventArrived += mew_EventArrived;
mew.Start();
}
}

public void TearDown()
{
if (mew != null)
{
mew.Stop();
mew.Dispose();
mew = null;
}
}

编辑:是的,我知道这不是您要找的答案,我认为无论如何都没有办法避免这种情况,用户必须知道如何使用该类...:/

关于c# - ManagementEventWatcher - 应用程序退出时出现 InvalidObjectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com