Managing Your WPF Splash Screen’s Lifecycle

A splash screen is created upon application startup and is ended after the the main Window class’s initialization code executes. Professional-looking applications geenrally use splash screens to let their users know where the application is in the initiliazation process. This generic splash screen is different from the SplashScreen (the .NET Framework 3.5 SP1) class provided by Microsoft, which displays only an image file and only in the center of the screen.

Sometimes, adding splash screens can be problematic. For instance, suppose you’ve added a WPF window to your project and spiced it up with some animation effects, which you implemented directly in XAML. Then, you specified the Startup event handler in the app.xaml file, like this:

In the App class, you added a property:

private static Thread threadSpashScreen;
public static Thread ThreadSpashScreen()
{
get { return app.threadSpashScreen };
}

You also added code for two methods as follows

private void Application_Startup(object sender, StartuoEventArgs e)
{
threadSpashScreen = new Thread(ExecuteSplashScreen);
threadSplashScreen.SetAppartmentState(AppartmentState.STA);
. . .
threadSplashScreen.Start();
}
private void ExecuteSplashScreen()
{
SplashScreen splScr = new SplashScreen();
. . .
splScr.ShowDialog(); //Modal dialog box
}

At the end of the main Window class’s initialization code, you’ve called Abort():

App.ThreadSplashScreen.Abort();

This works without any visible problems. Or so you think.

So What’s the Problem?
Now suppose that one day, you’re troubleshooting an exception in the application code and you enable the Managed Debugging Assistants (MDA) in the VS 2008 debugger. (For those following along at home, go to the Exceptions Dialog Box in the Debug\Exceptions…menu item.)

You start the application and as the splash screen started to disappear, a dialog boxappears with the following error message:

AsynchronousThreadAbort was detected
User code running on thread 5756 has attempted to abort thread 5404.

If the thread being aborted was in the middle of an operation that modifies a global state or uses native resources, this error could indicate a corrupt state or resource leak. Aborting threads other than the currently running thread is strongly discouraged.

The source of this problem is how you’ve managed the lifecycle of the splash screen.

Read the rest at DevX