WPF/C# - Window closes when it opens

c#, window, wpf

Solution

Your code is doing some strange things for which there is no apparent reason:

- Why create a new thread and then put the one you already have into an endless loop?

- Why call `.ToString()` on your `Window`, which additionally is owned by a different thread? (I 'm not sure if this would cause your program to crash due to the ownership issue like most other operations would, but it's probable).

Furthermore, you do not create a message loop anywhere so even if the program worked it would be completely unresponsive to user input. After creating your `Window`, in whatever thread you do it, you should call

System.Windows.Threading.Dispatcher.Run();

Problem

I try to open an wpf window in my c# test application. But when I open the window, it is immediately closed again. Whats wrong in my code? Main.cs (also available here): ``` namespace Project1 { class TestClass { public static MainWindow _mainWindow = null; static void Main(string[] args) { Thread t = new Thread(new ThreadStart(ThreadProc)); t.SetApartmentState(ApartmentState.STA); t.Start(); while (true) { System.Threading.Thread.Sleep(1000); _mainWindow.ToString(); } } public static void ThreadProc() { TestClass2 testClass = new TestClass2(); testClass.Open(); } } class TestClass2 { public void Open() { TestClass._mainWindow = new MainWindow(); TestClass._mainWindow.Show(); Console.WriteLine("=)"); } } } ``` MainWindow.xaml: http://paste.ubuntu.com/943800/

Original source