Reputation: 1897
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.
Upvotes: 3
Views: 2534
Reputation: 236218
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.
Upvotes: 4
Reputation: 564413
I would recommend writing this using Task
instead of thread. Since you're updating the UI in your completion, you need to make sure it runs in the UI thread. This can be done via a continuation:
Task task = Task.Factory.StartNew(() => GetAppUpdates());
task.ContinueWith(t => UpdateUserInterface(),
TaskScheduler.FromCurrentSynchronizationContext());
Upvotes: 0