Occasional thread abort exception

106 Views Asked by At

I've inherited some code from a previous developer and the app occasionally gives a thread abort exception when performing a certain task.

    private void popup()
    {

        Thread th = new Thread(() =>
        {
            try
            {
                OpenForm();
            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine("Thread was forcibly aborted");
            }
        });

        th.Start();
        while (fromflag)
        {
        }

        th.Abort();

    }

The thread opens a popup with an animated loading gif, downloads files from a server and then completes. I set fromflag to false when done. I can't set a timer as it can take any time to download the files.

How can I write this differently so then I don't have to use th.Abort and the thread closes itself when complete?

1

There are 1 best solutions below

3
Christopher On

You are opening a form on anotehr thread? That is some pretty bad design.

Usually all forms should be created by the GUI thread. If anotehr thread needs soemthing written, that is something Invoke is there for.

Without showing us the actuall code that is run in the thread (presumably contained in OpenForm()) we can not help you debugging at all.

While I can understand why the programmer used this shortcut (doing idle animations can require extra threads depending on teh Dispaly technolgoy), I still find this a bad design that should be reworked.