1

I started a thread inside a label click event. The thread did its job. I even got the last message box inside the thread. I want to execute some more instructions inside the label click event after finishing the thread. So I used an if statement with IsAlive property of the thread. Seems like thread's IsAlive property value is always true. How? How to make sure that all thread gonna end when I close the application or is it gonna end naturally when I close the application?

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;
}
master_yoda
  • 463
  • 3
  • 11
  • 5
    You realise that your check is executed immediately after you start the thread, as opposed to when it finishes? – GSerg Nov 19 '19 at 12:59
  • @GSerg But I haven't got ´´´MessageBox.Show("please enter the data"); ´´´ message. – master_yoda Nov 19 '19 at 13:05

1 Answers1

3

If you must use Thread, you can use Thread.Join to wait until the thread has completed.

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   
}

However, that will also lock up your UI while the thread is running, which means there isn't much difference between this and just calling ThreadedMethodForCalc directly.

To avoid that, you can use async/await and Task.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   
}

That will leave your UI responsive to user input while ThreadedMethodForCalc runs. However, you may have to disable some controls on your form to make sure that the user cannot do things they shouldn't be doing while that operation is running, and enable them again after. But that is a decision you'll have to make.

There is more information about asynchronous programming here: Asynchronous programming with async and await

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84