CodexBloom - Programming Q&A Platform

C# - implementing Async Method Returning Value in a Loop with Task.WhenAll

👀 Views: 1503 💬 Answers: 1 📅 Created: 2025-06-14
async-await httpclient tasks C#

I've searched everywhere and can't find a clear answer. I'm writing unit tests and I've been banging my head against this for hours. I'm running into a question with an asynchronous method that I'm trying to use to fetch data from an API in a loop. I'm using `Task.WhenAll` to execute multiple tasks concurrently, but it seems that I'm not getting the expected results when I attempt to return a list of values from my async method. Here's the code I'm working with: ```csharp public async Task<List<string>> FetchDataAsync(List<string> endpoints) { var tasks = endpoints.Select(async endpoint => { using (var client = new HttpClient()) { var response = await client.GetStringAsync(endpoint); return response; } }); var results = await Task.WhenAll(tasks); return results.ToList(); } ``` When I call this method like this: ```csharp var endpoints = new List<string> { "https://api.example.com/data1", "https://api.example.com/data2", "https://api.example.com/data3" }; var data = await FetchDataAsync(endpoints); ``` I get an behavior `InvalidOperationException: The result of the function is invalid due to being a Task`. It seems like the scenario is that I’m returning a task instead of the actual result from the API calls. I've tried separating the creation of the tasks from their execution, but that didn’t help. I also experimented with `Task.Run`, but that just added unnecessary complexity without solving the question. I'm running this on .NET 6.0, and I want to ensure I’m using best practices for async programming. How do I fix this so I can return the expected list of strings from my async method? My development environment is macOS. Is there a better approach? Cheers for any assistance! Thanks for your help in advance!