gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:07:12 25 4
gpt4 key购买 nike

我正在使用线程调用包含 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com