I have the following code that I have used for many years in .Net Framework 4.8 to show a splash screen on my startup:
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
WpfSplashScreen splash = new WpfSplashScreen();//Get stuck here!
splash.Show();
Thread.Sleep(3000);
splash.Close();
}));
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
//Loading some things...
Thread.Sleep(4000);
But after migrating my project to .Net 8 it stopped working like before. Now the new thread created to show the SplashScreen gets stuck at the dialog initializing and only continues after the main thread has finished, this causes my SplashScreen to only open after all loading is complete.
While debugging, if I step into 'WpfSplashScreen()' I can see that the thread stops at the 'InitializeComponent()' method.
I don't want to change my SlpashScreen to another component, that is not the idea here, I have used the same approach to open other dialogs on their own threads in many parts of my program for different reasons (like for example a progressbar window) and all cases have the same problem after migration. The SplashScreen is just the simplest example I have about this problem. So I really need to know how to make the Wpf dialog initialization not hang the separate thread in .Net 8.
Any idea?
Although your method worked, I still wouldn’t recommend doing it that way. In general, I would leave the explicit creation of threads for cases of extreme necessity, when it is impossible to do otherwise. The same applies to all UI elements. You should create and work with them only in the main application thread.
Therefore, I would suggest that you replace your code with the code I proposed below. And it’s better to replace the code not only in Core/Net applications, but also in the Framework.
Since you often use a display like this, you can create an extension method and use it: