【发布时间】:2015-09-12 21:13:16
【问题描述】:
我目前正在使用 observables 来管理总线上生成的消息,这些消息被推送到各种流中。
一切正常,但由于消息可以进入,系统可能会尝试一次将多条消息写入流(即来自多个线程的消息),或者消息的发布速度比写入速度快流...如您所见,这会在写入时引起问题。
因此,我试图弄清楚如何组织事物,以便在收到消息时一次只处理一个。有什么想法吗?
public class MessageStreamResource : IResourceStartup
{
private readonly IBus _bus;
private readonly ISubject<string> _sender;
public MessageStreamResource(IBus bus)
{
_bus = bus;
_senderSubject = new Subject<string>();
//`All` can publish messages at the same time as it's
//collecting data being generated from different threads
_bus.All.Subscribe(message => Observable.Start(() => ProcessMessage(message), TaskPoolScheduler.Default));
//Note the above hops off the calls context so that the
//writing to the stream wont slow down the caller.
}
public void Configure(IAppBuilder app)
{
app.Map("/stream", async context =>
{
...
await context.Response.WriteAsync("Lets party!\n");
await context.Response.Body.FlushAsync();
var unSubscribe = _sender.Subscribe(async t =>
{
//PROBLEM HERE
//I only want this callback to be executed
//one at a time...
await context.Response.WriteAsync($"{t}\n");
await context.Response.Body.FlushAsync();
});
...
await HoldOpenTask;
});
}
private void ProcessMessage(IMessage message)
{
_sender.OnNext(message.Payload);
}
}
【问题讨论】:
-
如果您使用 Rx,那么它会自动确保一次处理一条消息。这就是 Rx 为您所做的。
-
使用
_sender.Synchronize().Subscribe(...)有问题吗?
标签: c# .net task-parallel-library system.reactive observable