I am starting a WPF application from an MSTest (as a STA thread). I start the application in the assembly initialize and wait for it to complete loading. Both when I manually close the main window (which was opened from the test) and when I close it in the assembly cleanup (automated way), after the assembly cleanup method is finished I always get the COM object that has been separated from its underlying RCW cannot be used, only in test debug
exception.
I tried to wait for GC to finish and also call Dispatcher.CurrentDispatcher.InvokeShutdown();
in the cleanup as suggested in similar threads, but no luck.
Note, that in the actual test case I was not doing anything, as I wanted to minimize the scenario and make sure that this exception is thrown just by opening and closing the application. Of course, when I just run the application manually and not from the test, I don't get any exception when closing the window.
Any other suggestions to prevent this?
When running and no debugging my test, the execution completes successfully and VS can continue with running the tests of the next scheduled project (which is not related to starting the application).
Stack trace
PresentationCore.dll!System.Windows.Input.TextServicesContext.StopTransitoryExtension()
PresentationCore.dll!System.Windows.Input.TextServicesContext.Uninitialize(bool appDomainShutdown)
WindowsBase.dll!MS.Internal.ShutDownListener.HandleShutDown(object sender, System.EventArgs e)
Repro:
- Create a new C# WPF .NET Framework solution (eg.
WpfApp1
) - In the autogenerated
MainWindow.xaml
add a simple empty grid
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
- Add a
Program.cs
file with the following code:
public static class Program
{
[STAThread]
public static void Startup()
{
var window = new MainWindow();
window.Show();
window.Close();
}
}
- Create a C# MSTest project in the solution (eg.
UnitTestProject1
) - Add the WPF project as a reference in the MSTest project
- Add following code in the unit test class
[TestClass]
public class UnitTest1
{
[AssemblyInitialize]
public static void Initialize(TestContext _)
{
var mainThread = new Thread(() =>
{
WpfApp1.Program.Startup();
});
mainThread.SetApartmentState(ApartmentState.STA);
mainThread.Start();
mainThread.Join();
}
[TestMethod]
public void TestMethod1()
{
}
}
- Debug the
TestMethod1