Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify the UI Thread from Background Thread

I am trying to download some pages in the background, whose contents will be inserted into a database.

I need to do this on a background thread of some kind (either BackgroundWorker or ThreadPool, which is preferred due to the way I can queue things up), but I also need to update the UI when the jobs are done.

How can I notify the UI thread that the jobs are finished on Windows Phone?

I've seen someone use Dispatcher.beginInvoke, but it wasn't clear what he was using (either Worker or Pool)-- is this the correct way of doing this?

like image 719
Andrew M Avatar asked Jul 19 '11 15:07

Andrew M


People also ask

Can we update UI from thread?

Worker threads However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.

How do I run a thread in the background?

To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.

How do I notify another thread?

put(message) each time it has a new message and MainThread calls 'queue. take() which will block until there's a message to receive.


2 Answers

 Deployment.Current.Dispatcher.BeginInvoke(() =>
 {
      // change UI here
 });

Dispatcher allows you to run a piece of code on a thread.

Deployment class provides the application information of a silverlight-based application.

this is the code you need to use, actually this is the way you can run a piece of code on UI thread from another thread (no matter how and where that thread is running).

like image 142
Mo Valipour Avatar answered Oct 12 '22 12:10

Mo Valipour


Alternatively, if you're using MVVM, you could update the viewmodel off the UI thread and let the magic of INotifyPropertyChanged handle updating the UI for you.

like image 27
Matt Lacey Avatar answered Oct 12 '22 14:10

Matt Lacey