在循环中等待两件事? [英] awaiting two things in a loop?

查看:31
本文介绍了在循环中等待两件事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I await for two or more things (with different types) at the same time? Like in an event loop:

while(true) {
    Letter msg1 = await WaitForLetter();
    //read msg1 and reply.
    SMS msg2 = await WaitForSMS();
    //read msg2 and reply
}

这看起来不对.这两条消息最终会互相阻塞吗?

That doesn't look right. The two messages will end up blocking each other?

推荐答案

目前,您的代码将依次等待每个方法完成.如果你想发送每条消息然后等待最后,你可以使用 Task.WaitAll 方法(假设您的方法返回一个 Task 对象.

Currently, your code will wait for each method to finish in turn. If you want to send out each message then wait for both at the end, you can use the Task.WaitAll method (assuming your methods return a Task<T> object.

while(true) {
    Task<Letter> msgTask1 = WaitForLetter();
    Task<SMS> msgTask2 = WaitForSMS();

    Task.WaitAll(msgTask1, msgTask2);
}

然后您可以使用 Result 属性获取每个任务的结果(再次假设您的方法返回 Task:

You can then get the result of each task with the Result property (again assuming your method return Task<T>:

Letter msg1 = msgTask1.Result;
SMS msg2 = msgTask2.Result;

当然,这都是假设WaitForLetterWaitForSMS的实现是独立的,不会互相阻塞.

Of course, this all assumes the implementation of WaitForLetter and WaitForSMS are independent and don't block each other.

如果您只想等待任何任务完成,您可以使用`Task.WaitAny' 大致相同的结果.这将返回已完成任务的索引,以便您知道哪个已完成.

If you just want to wait for any of the tasks to finish, you can use `Task.WaitAny' to much the same end. This returns the index of the task that finished so you know which one is complete.

while(true) {
    Task<Letter> msgTask1 = WaitForLetter();
    Task<SMS> msgTask2 = WaitForSMS();

    var finishedTask = Task.WaitAny(msgTask1, msgTask2);
}

这篇关于在循环中等待两件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆