ReactiveUI 消息总线

发布于 2024-11-03 15:57:27 字数 324 浏览 1 评论 0原文

我正在测试ReactiveUI,它看起来非常好。

然而,我对MessageBus有点困惑。

示例代码:

var bus = new MessageBus();
int result = -1;

bus.Listen<int>().Subscribe(x => result = x);
bus.SendMessage(42);

它在调用 Assert 语句时确实有效,但在标准 WPF 应用程序中,结果值永远不会更新。这可能是由于 Scheduler 的实现造成的,但我还不太清楚。

欢迎任何提示。

I'm testing ReactiveUI, it seems very nice.

However, I am a bit puzzled by the MessageBus.

Sample code :

var bus = new MessageBus();
int result = -1;

bus.Listen<int>().Subscribe(x => result = x);
bus.SendMessage(42);

It does work when calling an Assert statement, but in a standard WPF application the result value is never updated. This is probably due to the Scheduler implementation, but it's not quite clear to me yet.

Any hint is welcome.

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

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

发布评论

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

评论(1

む无字情书 2024-11-10 15:57:27

结果最终会更新(与调用Dispatcher.BeginInvoke相同),而不是立即更新。默认情况下,RxUI 在单元测试运行程序中以不同的方式安排事情,以便更轻松地编写单元测试 - 这就是您在单元测试运行程序输出中看到该警告的原因。

如果您要执行以下操作:

var bus = new MessageBus();

bus.Listen<int>().Subscribe(x => MessageBox.Show("The answer is " + x));
bus.SendMessage(42);

您将看到消息框(如果没有,这肯定是一个错误!)。

为什么 MessageBus 会延迟?它使编写异步代码变得更加容易,因为您现在可以从其他线程发送消息,而不会因为访问错误线程上的对象而看到 WPF 可怕的 InvalidOperationException。

The result is eventually updated (the same as calling Dispatcher.BeginInvoke), not immediately. By default, RxUI schedules things differently in a unit test runner to make it easier to write unit tests - that's why you see that warning in the unit test runner output.

If you were to instead do something like:

var bus = new MessageBus();

bus.Listen<int>().Subscribe(x => MessageBox.Show("The answer is " + x));
bus.SendMessage(42);

You will see the Message Box (if not, it's definitely a bug!).

Why is the MessageBus deferred? It makes it easier to write async code, since you can now SendMessage from other threads without seeing WPF's dreaded InvalidOperationException due to accessing objects on the wrong thread.

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