To hydrate a dictionary with the results of async calls, you need to await the completion of each async call inside the lambda expression. Here’s how you can do it:
csharpusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public async Task<string> DoSomethingReturnString(int n)
{
// Simulating an async operation
await Task.Delay(100); // Replace this with your actual async call
return $"Result for {n}";
}
static async Task Main(string[] args)
{
Program program = new Program();
int[] numbers = new int[] { 1, 2, 3 };
Dictionary<int, string> dictionary = await Task.WhenAll(
numbers.Select(async n => new KeyValuePair<int, string>(n, await program.DoSomethingReturnString(n))))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
foreach (var kvp in dictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
}
}
In this example, Task.WhenAll
is used to await the completion of all async operations for each number. The Select
method is used to project each number to a KeyValuePair
, where the key is the number and the value is the result of the async operation. Finally, ToDictionary
is used to convert the sequence of KeyValuePair
into a dictionary.
المزيد من المعلومات
في هذا المثال، يتم استخدام Task.WhenAll
لانتظار اكتمال جميع العمليات الخاصة بـ async لكل رقم. يتم استخدام الطريقة Select
لتحويل كل رقم إلى KeyValuePair
، حيث يكون المفتاح هو الرقم والقيمة هي نتيجة العملية الـ async. وأخيرًا، يتم استخدام ToDictionary
لتحويل تسلسل KeyValuePair
إلى قاموس.
يمكنك استبدال الشيفرة التي تمثل عملية الانتظار await Task.Delay(100);
بالمكالمة الفعلية للدالة الخاصة بك التي تقوم بإرجاع القيمة النهائية بعد استكمال العملية الخاصة بـ async.