0

My string is empty when all the work is completed. Any solution for that?

string jsonString = "";
List<Task> tasksToWait = new List<Task>();

// ...

foreach (string blah in blahs)
{
    counter++;

    // ...
    
    Task task = new Task(async () =>
    {
        HttpResponseMessage response = await client.GetAsync(baseURL + URLparams);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        jsonString += responseBody + ",";
    });

    task.Start();
    tasksToWait.Add(task);

    if (counter == 50)
    {
        Task.WaitAll(tasksToWait.ToArray());
        tasksToWait.Clear();

        Console.WriteLine(jsonString);
    }
    
    // ...
}   

In an effort to speed things up, I am kicking off multiple API requests at once rather than wait for one at a time. Open to other options/solutions.

Thanks!

2
  • 1
    Why use new Task at all, given HttpClient is already async? Commented Aug 19, 2020 at 4:42
  • The reason the string is empty is because by using the Task constructor with an async lambda you end up with an async void lambda that can't be awaited. To fix this problem you must either use a Task<Task> constructor, or preferably the handy Task.Run. Look here for a more thorough explanation. Commented Aug 19, 2020 at 5:03

1 Answer 1

4

I'd suggest creating the tasks then awaiting them all with Task.WhenAll then use string.Join

They will be in the same order as they are in the list.

If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. The Result of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided

public async Task<string> DoStuff(string data)
{
   var response = await _client.GetAsync("");
   response.EnsureSuccessStatusCode();
   ...
   return await response.Content.ReadAsStringAsync();
}

Usage

var blahs = new List<string>();

var results = await Task.WhenAll(blahs.Select(DoStuff));

Console.WriteLine(string.Join(",",results));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.