我有一个方法可以在Form上写一些文本并在一个线程上运行。
当我通过一个按钮停止它时,它也会在盒子上写下一些文字但是在那个时候我的主要methot正在等待连接方法。
private void stop_btn_Click(object sender, EventArgs e)
{
A.stop_byuser(); //Some code with end with a log writing
foreach(Thread t in threads)
{
if (t.IsAlive)
t.Join();//Stops for finishing of thread
}
}
在完成之前,线程将进入我的日志编写代码并使用表单元素:
public void write_log(TextBox tb, String value)
{
if (tb.InvokeRequired) {
tb.Invoke(write_log_delegate, tb, value + "\n");//At here code is waiting
}
else
tb.Text += value + "\n";
}
我怎样才能消除这种无用的等待。
答案 0 :(得分:-1)
编辑:更改为更复杂的解决方案,以避免使用Abort(),如下所示:
在你的线程中,你需要一个循环来检查重置事件:
while (running)
{
/* Put thread code here */
if (stopEvent.WaitOne(500) || !running)
break;
}
然后使用WaitHandle.WaitAll()等待所有线程完成。
running = false;
foreach (var evt in stopEvents)
{
evt.Set();
}
// Wait for all threads to finish
WaitHandle.WaitAll(stopEvents);