C# Singleton UI 线程问题
我正在使用其他人编写的获取市场数据的服务。它连接到他们的服务器,你向它发送一个符号,它会发回数据。好吧,我正在尝试使用它打开多个视图,以便您可以获得多个交易品种的市场数据。完成此操作的方法是,我的 ViewModel 订阅单例事件 IncomingMessage,如果消息包含 ViewModel 的符号,则会将其放入 ObservableCollection 中。这就是问题所在。
如何将活动消息安全地添加到我的收藏中?
[编辑] 我相信抛出异常是因为我的 ObservableCollection 绑定到我视图上的 DataGrid。
I am using a service that someone else has written that gets market data. It connects to their server and you send it a symbol and it sends back data. Well I am trying to use it to have multiple Views open so you can get market data for more than one symbol. The way this is done is that my ViewModel subscribes to the singleton event IncomingMessage and if the message contains the ViewModel's symbol it puts it into an ObservableCollection. And that's where the problem is.
How can I add the message from the event to my collection safely?
[Edit]
I believe the exception is being thrown because my ObservableCollection is bound to a DataGrid on my view.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将对 Add 方法的调用封送至 UI 线程。在 Prism 中,这通常是通过事件聚合器完成的,但如果您不使用 prism:
假设您有某种类型
Tick
代表您的市场数据,并且数据事件只是一个System .Action
:或者,简单地说
You need to marshal the call to the Add method to the UI thread. In Prism this is usually done with the event aggregator, but if you are not using prism:
Assuming you have some type
Tick
that represents your market data, and that the data event is just aSystem.Action<Tick>
:or, simply
ObservableCollection
通常无法从后台线程更新。您需要使用Dispatcher.Invoke()
或Dispatcher.BeginInvoke()
来确保数据添加到集合所属的线程上。这是一项非常常见的任务,值得创建一个扩展方法来为您处理这个问题:
这样您就可以安全地进行几次击键并输入以下内容:
ObservableCollection<T>
generally can't be updated from background threads. You need to useDispatcher.Invoke()
orDispatcher.BeginInvoke()
to ensure that the data is added on the thread to which the collection belongs.That's a pretty common task, it's worthwhile to create an extension method to take care of this for you:
That way you can safe a few keystrokes and type this instead: