Skip to main content
 首页 » 编程设计

c#之使用带委托(delegate)的线程在 C# 中的线程中止异常

2024年02月23日17thcjp

我正在使用线程调用包含 while 循环的函数来读取权重。在 while 循环中,我调用委托(delegate)函数来更新文本框中的值。

单击名为 Stop 的按钮时,我试图中止该线程,但我收到了 Thread Abort 异常:

 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()); 
   }           
 } 

对于上面的代码,我得到了线程中止异常,任何人都可以帮助我解决这个问题。

请您参考如下方法:

改变

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

到

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

abort 立即停止线程,而 join 等待它完成。