Search code examples
c#delegatesthreadabortexception

Thread abort exception in C# using threads with delegates


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.


Solution

  • 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.