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

标签 c# delegates threadabortexception

我正在使用线程调用包含 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 等待它完成。

关于c# - 使用带委托(delegate)的线程在 C# 中的线程中止异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8008580/

相关文章:

c# - 获取 Firefox 网址

c# - ReaderWriterLockSlim 是否能抵抗 ThreadAbortException?

c# - 为什么在具有两个进程和输出重定向的代码中没有捕获到 ThreadAbortException?

c# - 从 MultipartFormDataContent 和 StreamContent 获取上传进度

c# - BindableBase 在经典 MVVM 设计中的使用

c# - 在运行时切换 wpf 资源字典

c# - 当对象是 Task<Something> 时获取 Func<object> 的结果

c# - 为什么在此代码中使用 Func<T>?

objective-c - applicationDidFinishLauching 从未被调用,WillFinishLauching 却被调用

DotNetOpenAuth.OpenId.RelyingParty.IAuthenticationRequest RedirectToProvider() ThreadAbortException