简体   繁体   English

与 Promise.all 等效的 C# 是什么?

[英]What is the C# equivalent to Promise.all?

I would like to fetch data from multiple locations from Firebase Realtime Database like described here and here by Frank van Puffelen and I can't find any equivalent to Promise.all in c#.我想从 Firebase 实时数据库中的多个位置获取数据,如 Frank van Puffelen在此处此处所述,我在 c# 中找不到与Promise.all等效的任何数据。 What would be the proper way to do it?什么是正确的方法呢?

That you are looking for is Task.WhenAll .您正在寻找的是Task.WhenAll You should create as many tasks as the multiple locations from which you want to fetch your data and then feed them in this method.您应该创建与要从中获取数据的多个位置一样多的任务,然后在此方法中提供它们。

To expand on @Christos's accepted answer:要扩展@Christos 接受的答案:

Task.WhenAll appears to be about as close as you will get for a drop-in replacement for Promise.all . Task.WhenAll似乎与您将获得的Promise.all替代品一样接近 I actually found it to be closer than I initially thought.我实际上发现它比我最初想象的更接近。 Here's an example using a JavaScript Promise.all implementation that you may want to replicate in C#:下面是一个使用 JavaScript Promise.all实现的示例,您可能希望在 C# 中复制它:

const [ resolvedPromiseOne, resolvedPromiseTwo ] = await Promise.all([ taskOne, taskTwo ]);

In C# you can do something very similar with Task.WhenAll (assuming they return the same types).在 C# 中,你可以用Task.WhenAll做一些非常相似的Task.WhenAll (假设它们返回相同的类型)。

var taskList = new[]
{
  SomeTask(),
  AnotherTask()
};

var completedTasks = await Task.WhenAll(taskList);

// then access them like you would any array
var someTask = completedTasks[0];
var anotherTask = completedTasks[1];

// or just iterate over the array
foreach (var task in completedTasks)
{
  doSomething(task);
}

This assumes they're both in async methods / functions.这假设它们都在async方法/函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM