I am showing a splash screen on a background thread while my program loads. Once it loads I am aborting the Thread as it's only purpose was to show a Now Loading splash form.
My problem is that when aborting a Thread it throws a ThreadAbortException
that the user can just click Continue on.
How do I deal with this? I was trying to suppress it like so -->
try
{
Program.splashThread.Abort();
}
catch(Exception ex)
{
}
but I have a feeling that is going to get me yelled at here and it doesn't work any way.
Thanks!
Some points. The ThreadAbort exception IS the reason the thread aborts. It is not a side effect of you calling abort. When you call abort on a thread, the runtime forces a threadabort exception to be propagated to the thread. This exception can be caught because it allows the user to perform some cleanup before the thread aborts.
The exception is then rethrown automatically to ensure that the thread is aborted. If the exception was caught and if it was not rethrown the thread would never abort.
Really intelligent design actually.
So it is really OK to catch that exception. In fact you should. But catch only that specific exception and not the general exception. (as shown below)
Change the exception type to ThreadAbortException and add a call to ResetAbort()
In general, aborting threads is considered very bad practice and can lead to all sorts of hard to track down bugs. Have you considered figuring out a way to just close the splash window or use some sort of polling to stop the thread when a flag has been set?
Using Threadabort is not recommened. It's evil. Why not use another mechanism like an (Auto/Manual)ResetEvent? Start the thread with the splash-screen, wait on the event. If the other code is done loading stuff, set the event en allow the splash-screen to close itself the normal (nice) way.
Try this code. It's working fine for me.
I've used the solution suggested by Fredrik Mörk. It's very clear and elegant. Otherwise I found a problem if we instantiate the splash form before launching the real application (application.run (mainform...)):
it raises an invalidOprationException caused by the form-handle still not exists in the calling-thread. To create the handle directly in the thread t (and skip this exception!) try to launch the splash form in this way:
and, if you plan to call the closeSplash method in more branches of the program, force the null value after the first call:
You don't need to cancel the thread. I'll exemplify with code.
In the splash screen form:
In the Program.cs file:
Now, when your Main method starts, show the splash in a thread:
...and when you want it to close, just close it:
Then you don't need to worry about aborting the thread; it will exit gracefully.