执行完以下两个测试用例后,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/