使用WPF退出时出现COM异常

Pat*_*key 13 c# com wpf rcw

执行以下两个测试用例后,将向控制台打印COM执行.我究竟做错了什么?

如果我单独运行任一测试,或者如果我同时运行两个测试,则会将异常写入控制台一次.这让我怀疑是否存在某种我不会清理的每AppDomain资源.

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

例外:

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)
Run Code Online (Sandbox Code Playgroud)

测试代码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bub*_*rap 20

再看一下我自己的代码,最后一行可能有助于WPF测试.

Dispatcher.CurrentDispatcher.InvokeShutdown();
Run Code Online (Sandbox Code Playgroud)