Running WPF on Another Thread

I’ve been developing a solution to meet an outlying need of mine and one of the requirements were that I needed to show a WPF window which lives inside a class library (DLL) that could be referenced by any application. Any WPF developer knows that WPF and other UI systems like WinForms require an STA thread apartment state to work properly, if at all. Unfortunately because my WPF UI is tucked inside a class library I don’t have control of the thread to ensure that it is in the required STA state.

The fix was easy, all I needed to do was spin up a new thread for the WPF UI and set that to STA and start the thread with a simple method that starts up my WPF window.

Thread wpfWindow = new Thread(new ThreadStart(ShowWpfWindow));
wpfWindow.SetApartmentState(ApartmentState.STA);
wpfWindow.Start();

private void ShowWpfWindow()
        {
            MyWindow window = new MyWindow();
            window.Show();
        }

Well my WPF window came and went in a flash, it just disappeared and if I wasn’t watching closely I would have never had noticed it was shown at all. My code worked, but it seems to join the thread and it completed a draw and then left, returning me to my main thread and closing everything. Well this wasn’t good, so I did some Googl’ing and determined that I needed to add a call to my ShowWpfWindow() method.

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

The Dispatcher is what is used by WPF to queue work items to be consumed by the UI thread. If the Dispatcher isn’t running the UI thread will have nothing to work on and just die. Hence why I saw the border by my new window but no content and it was gone in a flash. This needs to be called inside the thread that your starting the WPF application in, which is why I needed to add it to the last line of my ShowWpfWindow() method.

About: Shawn Jackson

I’ve spent the last 18 years in the world of Information Technology on both the IT and Development sides of the aisle. I’m currently a Software Engineer for Paylocity. In addition to working at Paylocity, I’m also the Founder of Resgrid, a cloud services company dedicated to providing logistics and management solutions to first responder organizations, volunteer and career fire departments, EMS, ambulance services, search and rescue, public safety, HAZMAT and others.