How to hydrate a Dictionary with the results of async calls?

前端 未结 4 1298
梦毁少年i
梦毁少年i 2020-12-10 11:21

Suppose I have code that looks like this:

public async Task DoSomethingReturnString(int n) { ... }
int[] numbers = new int[] { 1, 2 , 3};
         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 11:34

    If calling from an asynchronous method, you can write a wrapper method that creates a new dictionary and builds a dictionary by iterating over each number, calling your DoSomethingReturnString in turn:

    public async Task CallerAsync()
    {
        int[] numbers = new int[] { 1, 2, 3 };
        Dictionary dictionary = await ConvertToDictionaryAsync(numbers);
    }
    
    public async Task> ConvertToDictionaryAsync(int[] numbers)
    {
        var dict = new Dictionary();
    
        for (int i = 0; i < numbers.Length; i++)
        {
            var n = numbers[i];
            dict[n] = await DoSomethingReturnString(n);
        }
    
        return dict;
    }
    

提交回复
热议问题