我正在使用线程调用包含 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
等待它完成。
我是一名优秀的程序员,十分优秀!