问题描述
我正在尝试将多个(8)TcpStream
异步连接到服务。
目前,我在tokio
运行时中使用async
。
我正在努力弄清楚如何等待多个futures
并获得他们的Result
。
在C#
中,我可能会这样做:
C#
public Task ConnectAsync( IReadOnlyList<TcpClient> clients )
{
var tasks = new List<Task>( clients.Count );
foreach( var client in clients )
tasks.Add( client.ConnectAsync( "some address",32005 ) );
return Task.WhenAll( tasks );
}
上面的C#
代码是/正在尝试解决Rust
中相同问题的方式
铁锈
pub async fn connect( &self ) {
let mut futures = Vec::with_capacity( self.endpoints.len( ) );
for ep in &self.endpoints {
// The TcpStream is the tokio::net::TcpStream.
futures.push( TcpStream::connect(
format!( "{}:{}",ep.address( ),ep.port( ) ) ) );
}
// Here I would like to await for all of the futures
// to complete and then get the Result<Tcpstream>'s back...
}
我在这里的计划是await
让所有期货都完成,然后map
将结果Vec<TcpStream>
假定没有错误发生。
所以重申一下,我该如何等待存储在一个容器中的多个期货并在它们全部完成后获取结果?
此外,我是否可以正确解决此问题?我在想可能有更好的方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)