优雅地处理需要在调度程序线程上进行更改的集合更改

发布于 2024-09-11 20:19:16 字数 519 浏览 1 评论 0原文

这是我的情况:

我有一个从 ListCollectionView 中提取的用户界面 ItemsControl“ResultsPresenter”(WPF),该 ListCollectionView 使用非 UserInterface 类中的 BindingList“Results”作为 ListCollectionView.Source 属性。

时,我都会收到 NotSupportedException,坚持认为{“这种类型的 CollectionView 不支持从与 Dispatcher 线程不同的线程更改其 SourceCollection。”}

每当我对“结果”进行更改(例如添加操作) 此错误来自“Results”集合,但错误信息似乎明显是 WPF 生成的。我想知道为什么会抛出此错误,以及如何解决它而不将包含“结果”的类暴露给 WPF 相关代码。

注意:

此解决方案是在直接查看“Results”属性进行绑定时导致此错误后出现的,引入 ListCollectionView 只是为了尝试纠正这种情况,并且很可能不是问题的一部分。

Here's my situation:

I've got a User interface ItemsControl "ResultsPresenter" (WPF) pulling from a ListCollectionView that uses a BindingList "Results" from a non-UserInterface class as the ListCollectionView.Source property.

Whenever I make a change to "Results" such as an add operation, I get a NotSupportedException, insisting that {"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."}

It looks as if this error is coming from the "Results" collection, but the error information seems distinctly WPF generated. I'd like to know why I am throwing this error, and how to resolve it WITHOUT exposing the class that contains "Results" to WPF related code.

NOTE:

This solution came about after it was causing this error while looking directly at the "Results" property for binding, the ListCollectionView was only introduced to try and remedy this situation and is more than likely not part of the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

葬花如无物 2024-09-18 20:19:16

自 WPF 被称为 Avalon 以来,这一直是集合更改通知的一个已知问题。请参阅关于该主题的 Bea Stollnitz 的博客文章

您可以通过在调度程序线程上进行集合更改来轻松解决这个问题。因为我猜测您有一个长时间运行的操作返回项目或更改,所以我建议您查看 Rx 并使用 IObservable 的 ObserveOnDispatcher 设置。 Rx 一般来说,这种事情比以前容易得多过去。

This has been a known issue with collection changed notifications since WPF was called Avalon. See Bea Stollnitz's blog post on the subject.

You can work around it pretty easily by doing the collection changes on the dispatcher thread. Since I'm guessing you have a long running operation returning items or changes I'd recommend looking into Rx and using the ObserveOnDispatcher setting of IObservable. Rx in general makes this sort of thing much easier than it was in the past.

乙白 2024-09-18 20:19:16

Results 集合引发的事件由 ListCollectionView 处理以通知 UI。如果这种情况发生在非 UI 线程上,您会收到此异常。

因此,您永远不应该从非 UI 线程修改 UI 绑定集合,除非它明确支持它。我前段时间写了一个支持它的类,你可以找到它此处

The event raised by your Results collection is handled by the ListCollectionView to notify the UI. If this happens on a non-UI thread, you get this exception.

So you should never modify a UI-bound collection from a non-UI thread, unless it explicitly supports it. I wrote such a class that supports it some time ago, you can find it here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文