c# - 循环等待两件事?

标签 c# asynchronous task

如何同时等待两个或多个(不同类型的)事物?就像在事件循环中一样:

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/

相关文章:

c# - 我将如何在 PHP 中生成相同的 token ? (来自.NET)

c# - 在 LINQ 查询中使用 .Value 时出现问题

c# - IQueryable 转换

jsf - EJB @Asynchronous 检索 JSF 中实时插入的行似乎是线程锁定的

WCF - AsyncPattern=true 或 IsOneWay=true

javascript - 事件/异步语言列表

c# - 使用 Task 的异步和等待同步方法

java - Spring 任务

c# - 如何在不破坏现有客户端的情况下使用 C# 重新实现旧的 DCOM 服务器?

c# - 如何从等待非通用任务中获取任务结果