从单独的线程访问ViewModel属性 [英] Accessing ViewModel properties from separate thread

查看:436
本文介绍了从单独的线程访问ViewModel属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的wpf应用程序中,使用单独的线程调用viewmodel中的耗时操作.但是,此函数访问视图模型中绑定到视图中对象的多个属性.我尝试直接访问它们,但是我没有抱怨它们归UI线程所有.我想知道直接在线程之间使用它们的后果.

In my wpf application, a time consuming operation in my viewmodel is called using a separate thread. This function, however, accesses several properties in the viewmodel that are bound to objects in the view. I tried accessing them directly and I see no complaints on them being owned by the UI thread. I'm interested in knowing the consequences of using them directly between threads.

推荐答案

您可以从任何线程(包括读写)自由使用ViewModel.一个主要的例外是处理集合-数据绑定的集合必须在用户界面线程上写入,因为绑定不会自动编组到UI线程(就像简单的绑定一样).

You are free to use your ViewModel from any thread - including reading and writing. The one main exception is dealing with collections - data bound collections must be written to on the user interface thread, as the binding doesn't automatically marshal to the UI thread (like simple bindings do).

但是,您仍然应该考虑对所有写入进行适当的同步.正常的线程同步问题会发生,因为ViewModel只是另一个类.

However, you still should consider having proper synchronization in place for any writes. Normal thread synchronization issues will occur, as the ViewModel is just another class.

话虽这么说,通常来说,您希望处理同步的方式与许多情况下略有不同.锁定通常不适用于ViewModel,因为WPF数据绑定不会锁定对象.因此,当需要在ViewModel中进行同步时,通常应根据需要使用Dispatcher.Invoke/BeginInvoke将调用编组回用户界面线程.

That being said, typically, you'll want to handle synchronization slightly differently than you would in many cases. Locks don't typically work on a ViewModel, as the WPF data binding will not lock the objects. As such, you should normally use Dispatcher.Invoke/BeginInvoke to marshal calls back to the user interface thread as needed when synchronization is required in the ViewModel.

这篇关于从单独的线程访问ViewModel属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆