c# - 使用 WPF 退出时出现 COM 异常

标签 c# wpf com rcw

执行完以下两个测试用例后,COM 执行将打印到控制台。我做错了什么?

如果我单独运行其中一个测试,或者如果我同时运行两个测试,异常只会被写入控制台一次。这让我怀疑我没有清理某种按 AppDomain 的资源。

我已尝试使用 NUnit 和 MSTest 进行测试,两种环境中的行为相同。 (实际上,我不确定在 MSTest 中运行这两个测试是否会导致一个或两个异常打印输出。)

异常(exception):

System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.
at System.Windows.Input.TextServicesContext.StopTransitoryExtension()
at System.Windows.Input.TextServicesContext.Uninitialize(Boolean appDomainShutdown)
at System.Windows.Input.TextServicesContext.TextServicesContextShutDownListener.OnShutDown(Object target)
at MS.Internal.ShutDownListener.HandleShutDown(Object sender, EventArgs e)

测试代码:

using NUnit.Framework;

namespace TaskdockSidebarTests.Client
{
    [TestFixture, RequiresSTA]
    public class ElementHostRCWError
    {
        [Test]
        public void WinForms()
        {
            var form = new System.Windows.Forms.Form();
            var elementHost = new System.Windows.Forms.Integration.ElementHost();
            form.Controls.Add(elementHost);

            // If the form is not shown, the exception is not printed.
            form.Show();

            // These lines are optional. The exception is printed with or without
            form.Close();
            form.Controls.Remove(elementHost);
            elementHost.Dispose();
            form.Dispose();
        }

        [Test]
        public void WPF()
        {
            var window = new Window();

            // If the window is not shown, the exception is not printed.
            window.Show();

            window.Close();
        }
    }
}

最佳答案

再次查看我自己的代码,以下行可能有助于 WPF 测试,就在最后。

Dispatcher.CurrentDispatcher.InvokeShutdown();

关于c# - 使用 WPF 退出时出现 COM 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232867/

相关文章:

c# - C++和C#之间HRESULT的转换

c# - 如何在Unity3d中测量两条线段之间的距离

C# WPF ListView动态个性化每一行的字体大小

c# - 派生 FixedDocument 的序列化

c++ - IEnumString::Next 的资源管理契约是什么?

c - 我应该 IUnknown::Release 使用 DllGetClassObject 创建的接口(interface)吗

c# - 用另一个替换字符串的一部分

c# - Try/Catch 没有捕捉到 WebException

linux - 我可以在依赖于 COM 组件的 Mono 上运行 .NET 对象吗?

c# - WPF 将文本从一个窗口传递到另一个窗口