2

I really don't know how to properly get data from a Thread.

In a thread (or Task, doesnt matter) i want to calculate a lot of doubles. When this is finished i want to show this data in a grid and in a graphic-chart. So i tried to return some type of

 Observable<List<double>>

When i then wanted to create a "new ViewModel(data)", i get exceptions cause of threads.

So how do i properly get such a list back from a thread and use it in UI? Or maybe pass this data while calculating to show some live values would also be nice..

thanks for answers, just need a few tips

  • You would usually use the Dispatcher of the UI thread. Start reading the Remarks section on [this MSDN page](http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx). There is also an MSDN article about the [Threading Model](http://msdn.microsoft.com/en-us/library/ms741870.aspx) in WPF. – Clemens Oct 21 '14 at 11:40

1 Answers1

1

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.

Community
  • 1
  • 1
Sheridan
  • 68,826
  • 24
  • 143
  • 183