none
C# Thread Aborting RRS feed

  • Question

  • I have use Thread to view a waiting form while my main form is loading in Load event. But sometimes I get an `ThreadAbortException` That says "Thread was being aborted."
    Here is my Code.
    Please help me to fix this problem.
    Thanks.
    Main Form Load event code:
    WaitingForm wf;
    MainForm_Load(object sender, EventArgs e)
    {
            Thread t = new Thread(new ThreadStart(delegate
            {
                wf = new WaitingForm();
                wf.ShowDialog();
            }));
            t.Start();
    
            /***** Do Something *****/
    
            if (wf != null)
                wf.closeLoad();
            t.Abort();
    }


    WaitingForm CloseLoad Function:

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


    Sunday, December 2, 2018 2:56 PM

Answers

  • Because you always close the form using closeLoad, then the thread will continue after wf.ShowDialog() and will terminate automatically, since there is nothing else to do, and there are no loops inside your thread procedure.


    • Marked as answer by Seena Fallah Tuesday, December 4, 2018 3:18 PM
    Sunday, December 2, 2018 7:35 PM

All replies

  • I think that you do not have to execute ‘t.Abort’. Does it work without this call?


    Sunday, December 2, 2018 7:21 PM
  • Yes but doesn't it need to be abort or interrupt?
    Sunday, December 2, 2018 7:22 PM
  • Because you always close the form using closeLoad, then the thread will continue after wf.ShowDialog() and will terminate automatically, since there is nothing else to do, and there are no loops inside your thread procedure.


    • Marked as answer by Seena Fallah Tuesday, December 4, 2018 3:18 PM
    Sunday, December 2, 2018 7:35 PM
  • but after the closeLoad function when I see the t.ThreadState it says that its running!
    Sunday, December 2, 2018 7:47 PM
  • This means that it did not yet finish in your particular experiment (maybe because Debugger paused it when you use the Watch window to check the state). This does not mean that the thread is eternal.

    If you let the thread to continue, then display the state later or using MessageBox, maybe after short Sleep, you will see that the state is Stopped.


    Sunday, December 2, 2018 8:47 PM