我正在尝试使用C#中的Rebus
作为Javaorg.greenrobot.eventbus.EventBus
的替代品。无法弄清楚如何动态注册处理程序。
目标:
- 启动巴士
- 在运行时动态注册处理程序(例如,当用户按下按钮时添加新处理程序(
- 通过这些处理程序接收一些消息
- 停止巴士
当前代码:(NUnit( 它只打印 Rebus 本身的一些诊断输出,而不打印消息。
using System;
using System.Threading.Tasks;
using Rebus.Config;
using Rebus.Transport.InMem;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Handlers;
[TestFixture]
public class RebusTests
{
BuiltinHandlerActivator activator = new BuiltinHandlerActivator();
InMemNetwork network = new InMemNetwork(true);
private string inputQueueName = "inputQueue";
[SetUp]
public void Setup() {
Configure.With(activator)
.Transport(t => t.UseInMemoryTransport(network, inputQueueName))
.Start();
}
[TearDown]
public void Cleanup() {
activator.Dispose();
}
[Test]
public void TestHandlingStrings() {
var h1 = new StringHandler("handler 1");
var h2 = new StringHandler("handler 2");
int workersCount = activator.Bus.Advanced.Workers.Count;
activator.Bus.Advanced.Workers.SetNumberOfWorkers(0);
activator.Register(() => h1);
activator.Register(() => h2);
activator.Bus.Advanced.Workers.SetNumberOfWorkers(workersCount);
activator.Bus.Advanced.SyncBus.SendLocal("Good day, sir.");
}
}
public class StringHandler : IHandleMessages<string> {
public readonly string handlerName;
public StringHandler(string handlerName) {
this.handlerName = handlerName;
}
public Task Handle(string message) {
Console.WriteLine($"1) Handler [{handlerName}] got: {message}");
return Task.Run(() => { Console.WriteLine($"2) Handler [{handlerName}] got: {message}"); });
}
}
代码
[Test]
public void TestHandlingStrings() {
var h1 = new StringHandler("handler 1");
var h2 = new StringHandler("handler 2");
int workersCount = activator.Bus.Advanced.Workers.Count;
activator.Bus.Advanced.Workers.SetNumberOfWorkers(0);
activator.Register(() => h1);
activator.Register(() => h2);
activator.Bus.Advanced.Workers.SetNumberOfWorkers(workersCount);
activator.Bus.Advanced.SyncBus.SendLocal("Good day, sir.");
}
几乎会立即离开,所以公共汽车可能永远不会收到任何东西。
如果您在测试结束时插入一点Thread.Sleep(TimeSpan.FromSeconds(2));
,我敢打赌您的消息会收到:
[Test]
public void TestHandlingStrings() {
var h1 = new StringHandler("handler 1");
var h2 = new StringHandler("handler 2");
int workersCount = activator.Bus.Advanced.Workers.Count;
activator.Bus.Advanced.Workers.SetNumberOfWorkers(0);
activator.Register(() => h1);
activator.Register(() => h2);
activator.Bus.Advanced.Workers.SetNumberOfWorkers(workersCount);
activator.Bus.Advanced.SyncBus.SendLocal("Good day, sir.");
Thread.Sleep(TimeSpan.FromSeconds(2));
}