Starting a WPF window in a new thread

Apr 8, 2014 at 4:18 AM
Edited Apr 8, 2014 at 4:19 AM
Hello,

I am trying to create a WPF window in a thread which I initiate at end of the Start() function using the following code:
 SafeThread worker = new SafeThread(delegate()
            {
                myThread();
            }, "App-worker", logger);
            worker.SetApartmentState(ApartmentState.STA);
            worker.Start();
The myThread function just displays a WPF window.
public void myThread()
        {
            WPFwindow w1 = new WPFwindow();
            w1.Show();
        }
When I run the platform, the window pops up for a couple of seconds and goes away. So it looks like the thread is getting killed. If I am not wrong, we do a similar operation in the Dummy App where worker thread just keeps sending echo requests after every 10 seconds. Why is the thread being killed in this case?
Coordinator
Apr 8, 2014 at 5:17 AM

Hmm…really hard to tell from this description as to what is going on. Nothing fundamentally wrong with what you are doing; we have done similar things in the past.

1. Do you see any error message on the console?

2. If the thread wasn’t opening a window, but (say) was sitting in a loop printing stuff, does it still get killed?

Apr 8, 2014 at 5:46 AM
Thanks Ratul for your quick response!

So here are the answers to your questions:
  1. I do not see any errors on the console nor are any exceptions thrown.
  2. I tried printing a string in a while(true) loop and the thread does not get killed. The string gets printed infinitely.
Coordinator
Apr 8, 2014 at 5:55 AM

Could the problem then be with your windowing code?

If you call it directly without HomeOS, does it survive?

Apr 8, 2014 at 6:08 AM
Ah! I was thinking totally in the wrong direction. The problem seems like its indeed with the windowing code. I created a simple project with the same code and behavior gets repeated.

Thank you so much for you help!

-Piyush
Apr 8, 2014 at 6:27 AM
Actually one stackoverflow thread suggested that I use
System.Windows.Threading.Dispatcher.Run();
after the window was called. That helps to keep the window open.
Marked as answer by piyushw on 4/7/2014 at 11:30 PM