4

I am creating a new thread to call a function in it.

Thread th = new Thread(My_Function);
th.start();

I wanna do something on completion of this thread execution.

Is there any way of doing this ?

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83

2 Answers2

12

At least two possible solutions:

BackgroundWorker

Use a BackgroundWorker to execute your code, and use the RunWorkerCompleted event to execute the code that is run after completion.

A BackgroundWorker wraps the event based asynchronous pattern into a very easy to use mechanism, complete with progress reporting and cancellation. See this BackgroundWorker tutorial and this SO answer .

Tasks (.NET 4.0 and above)

Use a Task object, and use the ContinueWith method to define the code that needs to be executed after completion of the first task.

Community
  • 1
  • 1
Rotem
  • 21,452
  • 6
  • 62
  • 109
  • The Task link is very good. I ended up with something like Task.Run(() => MessageBox.Show("Step 0")).Wait(); Task.Run(() => MessageBox.Show("Step 2")).Wait(); which worked perfectly. – Wade Hatler Nov 19 '20 at 21:57
-2

You can use something such

if(th.isAlive())
{...}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mihai8
  • 3,113
  • 1
  • 21
  • 31