This kind of functionality is common and is often accomplished using the BackgroundWorker
Class. There is a code example on the linked page and you can find another with feedback in my answer to the How to correctly implement a BackgroundWorker with ProgressBar updates? question on this website.
Alternatively, you can use the Dispatcher
object from the UI thread to pass values to that thread. Note that each thread has it's own Dispatcher
, so be sure to call the one from the UI thread. You can use this little helper method:
public object RunOnUiThread(Delegate method)
{
return Dispatcher.Invoke(DispatcherPriority.Normal, method);
}
You can use it like this:
RunOnUiThread((Action)delegate
{
// You can run any number of lines of code on the UI Thread here
});
Or inline, like this:
RunOnUiThread((Action)delegate { UpdateData(); });
I have this method in a separate class that has constructors like this:
private UiThreadManager(Dispatcher dispatcher)
{
Dispatcher = dispatcher;
}
public UiThreadManager() : this(Dispatcher.CurrentDispatcher) { }
I call this constructor on the UI thread to ensure that the Dispatcher
that I will be using is in fact the Dispatcher
from the UI thread.