c# - 我应该如何从 P&P 为 EventAggregator 创建事件,以便 UI 线程上的订阅者可以收听它们?

标签 c# eventaggregator

我正在尝试在后台任务运行时更新主窗体中的进度条。

我正在使用来自最新模式和实践发布路线的 EventAggregator 我的应用程序范围事件。

我正在从一个监听BackgroundWorker事件的类中触发一个事件,然后触发一个事件:

  1. bw 上的进程触发 BW 方法 报告进展情况。
  2. BW 火了 报告事件。
  3. 他们被选中 通过 SomeCommand 类方法 之前已在 BW 上设置 已启动。
  4. 我发布的事件来自 事件聚合器

public void ProgressChanged(对象发送者,ProgressChangedEventArgs ea) { KnownProgressStatusChangedEvent evt = KernelKeeper.Kernel.Get().GetEvent(); evt.Publish(ea); }

我的 MainPresenter 已订阅这些事件,如下所示:

    KnownProgressStatusChangedEvent progressChanged = EventAggregator.GetEvent<KnownProgressStatusChangedEvent>();
    progressChanged.Subscribe(KnownProgressChanged,ThreadOption.UIThread);

如果我不设置 ThreadOption.UIThread,我会在 Program.cs 中收到 TargetInvokationException,并且没有堆栈跟踪。 这样我就不会出现异常,并且可以进入 EventAggregator。

当它要调用 KnownProgressChanged 方法时,它会尝试调用该方法并检查 Application.Current != null。它为 null,并且没有任何内容被触发。

我做错了什么?请指教。

最佳答案

您必须指定 ThreadOption.UIThread,因为您正在处理进度条,必须从 ui 线程调用处理程序才能绘制新的进度状态。

但是,如果您使用 WPF,则必须在没有 ThreadOption.UIThread 和 dispatch 的情况下处理它。自己调用的话,可以看一下CompositeWpfEvent。

参见Event Aggregator - 在用户界面线程上订阅

Frequently, subscribers will need to update user interface elements in response to events. In Windows Presentation Foundation (WPF), only a UI thread can update user interface elements. By default, the subscriber receives the event on the publisher's thread so if the publisher sends the event from the UI thread, the subscriber will be able to update the user interface.

However, if the publisher's thread is a background thread, the subscriber may be unable to directly update user interface elements. Instead, it would need to schedule the updates on the UI thread using the Windows Presentation Foundation's Dispatcher class. The CompositeWpfEvent provided with the Composite Application Library can assist by allowing the subscriber to automatically receive the event on the UI thread. The subscriber must indicate this during subscription, as shown in the following code.

...

关于c# - 我应该如何从 P&P 为 EventAggregator 创建事件,以便 UI 线程上的订阅者可以收听它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1764833/

相关文章:

C#获取系统网络使用情况

c# - 如何在 URL 中隐藏扩展名(例如 .aspx)?

c# - MVVM Light Toolkit - Messenger 使用事件聚合器或调解器模式?

c# - 使用 Reactive Extensions 的事件聚合器问题

c# - Jon Skeet 单例和 EventAggregator

.net - SOLID 和事件聚合器

c# - 将 C 中包含 unsigned char 指针的代码移植到 C#

c# - 如何将一系列名称分成不同的行

c# - 带有自定义轴标签的 xaml c# 图表

c# - 将 Rx 与 Prism 的 EventAggregator 一起使用或与其一起使用 - 建议的方法?