Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Threading Issue - Need Event after thread completes

I'm designing a multi-threaded process where I create a thread to do some processing so as to not lock the UI. However, when this thread completes (if it completes succesfully w/o error) I need an event so I can execute a method on the UI thread that will update the UI properly.

How can I accomplish this correctly?

My simple code for the Thread:

Thread t = new Thread(new ThreadStart(GetAppUpdates));
t.Start();

Now I need to know when the thread completes, but I feel that I don't want to implement code that would constantly check the Thread State because it would cause UI delay.

(I know this is easier with backgroundworker but I don't want a backgroundworker for this process because this Thread cannot be background).

Is there a way to trigger events for Thread objects when they complete? What is the best way to accomplish a ThreadFinished() event? I have code that must be executed on the Main UI after Thread successful completion.

like image 647
Encryption Avatar asked Mar 22 '26 01:03

Encryption


1 Answers

Pass new anonymous method, which calls GetAppUpdates() and some other method, which notify you about getting updates completed:

Thread t = new Thread(new ThreadStart(() => { GetAppUpdates(); Completed(); }));
t.Start();

Completed method will be called after your GetAppUpdates() method will be executed:

private void Completed()
{
   if (InvokeRequired)
   {
      Invoke((MethodInvoker)delegate() { Completed(); });
      return;
   }

   // update UI
}

BTW This will do the job, but I'd better go with BackgroundWorker - it is designed for such tasks, and it's RunWorkerCompleted event handler will run on UI thread, which is very handy.

like image 199
Sergey Berezovskiy Avatar answered Mar 24 '26 16:03

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!