How do I suppress a thread.abort() error C#?

Refracted Paladin picture Refracted Paladin · Jun 4, 2009 · Viewed 10.8k times · Source

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!

Answer

Fredrik Mörk picture Fredrik Mörk · Jun 4, 2009

You don't need to cancel the thread. I'll exemplify with code.

In the splash screen form:

public void CloseSplash()
{
    Invoke((MethodInvoker)delegate
    {
        this.Close();
    });
}

In the Program.cs file:

private static Splash _splash = null;
public static void CloseSplash()
{
    if (_splash!= null)
    {
        _splash.CloseSplash();
    }
}

Now, when your Main method starts, show the splash in a thread:

Thread t = new Thread(new ThreadStart(delegate
{
    _splash = new Splash();
    _splash.ShowDialog();
}));

t.Start();

...and when you want it to close, just close it:

Program.CloseSplash();

Then you don't need to worry about aborting the thread; it will exit gracefully.