我真的不知道如何正确地从线程中获取数据。
在线程(或任务,无关紧要)中,我想要计算大量的doubles。当这项工作完成后,我想在网格和图表中显示这些数据。所以我试着返回一些类型的
Observable<List<double>>然后,当我想创建一个“新的数据(ViewModel)”时,我得到了线程引起的异常。
那么,如何正确地从线程中获取这样的列表并在UI中使用它呢?或者,在计算时传递此数据以显示一些实时值也会更好。
谢谢你的回答,只需要一些提示
发布于 2014-10-21 20:32:54
这类功能很常见,通常使用BackgroundWorker Class来实现。链接页面上有一个代码示例,您可以在本网站上我对How to correctly implement a BackgroundWorker with ProgressBar updates?问题的回答中找到另一个带有反馈的示例。
或者,您可以使用UI线程中的Dispatcher对象将值传递给该线程。请注意,每个线程都有自己的Dispatcher,因此一定要从UI线程调用它。您可以使用这个小帮助器方法:
public object RunOnUiThread(Delegate method)
{
return Dispatcher.Invoke(DispatcherPriority.Normal, method);
}你可以这样使用它:
RunOnUiThread((Action)delegate
{
// You can run any number of lines of code on the UI Thread here
});或者内联,就像这样:
RunOnUiThread((Action)delegate { UpdateData(); });我在一个单独的类中有这个方法,它有如下的构造函数:
private UiThreadManager(Dispatcher dispatcher)
{
Dispatcher = dispatcher;
}
public UiThreadManager() : this(Dispatcher.CurrentDispatcher) { }我在UI线程上调用此构造函数,以确保我将使用的Dispatcher实际上是来自UI线程的Dispatcher。
https://stackoverflow.com/questions/26485379
复制相似问题