如何同时等待两个或多个(不同类型的)事物?就像在事件循环中一样:
while(true) {
Letter msg1 = await WaitForLetter();
//read msg1 and reply.
SMS msg2 = await WaitForSMS();
//read msg2 and reply
}
这看起来不对。这两条消息最终会互相阻塞吗?
最佳答案
我认为您最好的选择是使用 Microsoft 的 Reactive Framework(NuGet“Rx-Main”)。它与 Tasks 配合得很好。
这是您需要的代码:
var subscription1 =
Observable
.FromAsync(WaitForLetter)
.Repeat()
.Subscribe(msg1 =>
{
//read msg1 and reply.
});
var subscription2 =
Observable
.FromAsync(WaitForSMS)
.Repeat()
.Subscribe(msg2 =>
{
//read msg2 and reply
});
两者相互独立运行,并且都异步运行。
要停止运行,只需执行以下操作:
subscription1.Dispose();
subscription2.Dispose();
如果你真的希望它们像事件循环一样运行,消息都进入同一个线程,相互穿插,那么你可以这样做:
var eventLoopScheduler = new EventLoopScheduler();
var subscription1 =
Observable
.FromAsync(WaitForLetter)
.Repeat()
.ObserveOn(eventLoopScheduler)
.Subscribe(msg1 =>
{
//read msg1 and reply.
});
var subscription2 =
Observable
.FromAsync(WaitForSMS)
.Repeat()
.ObserveOn(eventLoopScheduler)
.Subscribe(msg2 =>
{
//read msg2 and reply
});
你有更多的清理工作,但这可以很好地处理:
var subscriptions = new CompositeDisposable(
subscription1,
subscription2,
eventLoopScheduler);
//then later
subscriptions.Dispose();
关于c# - 循环等待两件事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983882/