Thread abort exception in C# using threads with delegates

3.4k views Asked by At

I am using a thread to call a function containing a while loop to read a weights. In the while loop, I am calling a delegate function to update values in a text box.

On clicking a button named Stop, I am trying to abort the thread, but I am getting a Thread Abort exception:

 private System.Threading.Thread comm1;
 comm1 = new System.Threading.Thread(new System.Threading.ThreadStart(reading));
 comm1.Start();

 public void reading()
 {
   while(continus)
   {
     textBox1.Invoke(
                     new PrintValueTextDelegate(PrintValueText), 
                     new object[] { text Box, value.ToString() });

     for (int i = 0; i < risposta.Length; i++)
     {
        risposta[i] = 0;
     }

     if (_protocollo.Manda_TLC1(2, 0x70, risposta) == true)
     {
        if ((risposta[0] & 0x80) != 0x80)
        {
           cella = risposta[1] * 256 + risposta[2];
           string rt = cella.ToString();
        }
      }
   }
 }

 private void btnstop_Click(object sender, EventArgs e)
 {
   try
   {
      continus = false;             
      System.Threading.Thread.Sleep(1000);               
      comm1.abort(); // wait for close foreground thread 
   }
   catch (Exception rt)
   {
       MessageBox.Show(rt.ToString());
   }          
 }

For the above code I am getting thread abort exception can any one please help me out with this problem.

4

There are 4 answers

1
kͩeͣmͮpͥ ͩ On BEST ANSWER

change

comm1.abort();// wait for close foreground thread 

to

comm1.join();// wait for close foreground thread 

abort halts the thread immediately, whereas join waits for it to finish.

1
Chris On

You are getting a thread abort exception because you are telling the thread to abort...

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx (whcih isn't working for me at the moment but I grabbed text from google's cache) says:

The exception that is thrown when a call is made to the Abort method.

Note that this is not an exception telling you that your call to Thread.Abort() has failed, it is an exception from the thread you are aborting saying "Argh! I've just been aborted!".

If you want to stop more gracefully then make your stop call change your continus variable in your while loop to false. Then the while loop will stop running and your thread should finish.

0
Coding Flow On

Calling Thread.Abort() throws a thread abort exception, that is how it works.

See the docs "Raises a ThreadAbortException in the thread on which it is invoked"

0
GeirGrusom On

Use CancellationTokenSource to issue a cancel operation to a thread. Note that your application must check if cancellation has been requested. Use thread.Join to wait for a thread to exit.