【问题标题】:Why thread IsAlive returns false even after executing the last command inside the thread [duplicate]为什么即使在线程内执行最后一个命令后,线程 IsAlive 也会返回 false [重复]
【发布时间】:2020-03-15 00:12:18
【问题描述】:

我在标签点击事件中启动了一个线程。线程完成了它的工作。我什至得到了线程内的最后一个消息框。完成线程后,我想在标签单击事件中执行更多指令。所以我使用了if 语句和线程的IsAlive 属性。似乎线程的IsAlive 属性值始终为true。如何?如何确保我关闭应用程序时所有线程都会结束,或者当我关闭应用程序时它会自然结束?

private void lbl_Calc_Click(object sender, EventArgs e)
{
  Label label = (Label)sender;            
  //new thread to do the calc
  Thread t = new Thread(() => ThreadedMethodForCalc(label));
  t.Start();

  //checking the IsAlive property
  //but doesn't work

  if (t.IsAlive==false)
  {
       MessageBox.Show("please enter the data");  
       //more instruction here   
  }
}

private void ThreadedMethodForCalc(Label label)
{ 
  //calculation. not shown
  MessageBox.Show("end of thread");  //executed
  return;
}

【问题讨论】:

  • 您意识到您的检查是在您启动线程后立即执行的,而不是在它完成时?
  • @GSerg 但是我没有 ´´´MessageBox.Show("please enter the data"); '''消息。

标签: c# multithreading


【解决方案1】:

如果您必须使用Thread,您可以使用Thread.Join 等待线程完成。

private void lbl_Calc_Click(object sender, EventArgs e)
{
  Label label = (Label)sender;            
  //new thread to do the calc
  Thread t = new Thread(() => ThreadedMethodForCalc(label));
  t.Start();

  t.Join(); //wait until the thread completes

  MessageBox.Show("please enter the data");  
  //more instruction here   
}

但是,这也会在线程运行时锁定您的 UI,这意味着这与直接调用 ThreadedMethodForCalc 没有太大区别。

为避免这种情况,您可以使用async/awaitTask.Run

private async void lbl_Calc_Click(object sender, EventArgs e)
{
  Label label = (Label)sender;            
  //new thread to do the calc
  await Task.Run(() => ThreadedMethodForCalc(label));

  MessageBox.Show("please enter the data");  
  //more instruction here   
}

这将使您的 UI 在 ThreadedMethodForCalc 运行时响应用户输入。但是,您可能必须禁用表单上的某些控件,以确保用户在该操作运行时不能做他们不应该做的事情,并在之后再次启用它们。但这是你必须做出的决定。

这里有更多关于异步编程的信息:Asynchronous programming with async and await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多