I have a WPF Window which takes a lot of time to create and show. The user should be able to open one ore more of this windows.
Now, I am searching a way to improve the performance. One Idea is to create two of this Windows at the startup of the Application (when It shows the splash-screen). After I have only to show and hide this windows (and change the attached viewmodel). This should not be a problem. But when the user is working with the application and he uses the two windows which are loaded at startup of the application, I should load a third instance of the window in background. Now, the application should no be blocked when It loads the third one (or the 4. oder 5. etc.). Now, I am searching a way to do this. Would it be possible to load the window in another thread and after transfer it to the main UI thread?
Or are there other scenarios to reach the goal?
Thanks for any help.
Best Regards, Thomas
When you create a WPF object — Window, UserControl, or anything else that descends from DispatcherObject — it locks itself to the thread it was created on. So you can’t load the window in a background thread and then transfer it to the main UI thread. If you’re going to create it in a background thread, it needs to stay on that thread; it needs to be shown by that thread, and have a message pump on that thread.
But that’s viable. You could start a background thread, create your window there, and then wait for the main thread to say, “Okay, it’s time to show the window”. Then your thread could call Application.Run to start its own message pump, and shut itself down when the window closes.
Of course, multithreading opens up all kinds of new complications. You probably need a dedicated thread for each window (the thread pool isn’t likely to work for this). You need to handle all the inter-thread communication. If the windows access any shared data, you need to protect it with some sort of locking. You need to make sure the application exits when it should (and if that means “when all the windows are closed”, then you need to make sure you protect the “count of open windows” resource). There are probably other complications as well. Don’t enter into this lightly.
Your best bet, as others have said, is to profile your code and try to address your performance problems first. But if you’re convinced that you’ve done as much performance work as you can, multithreading and background loading could be an option to explore.