flashsplat
flashsplat

Reputation: 537

C# - Can multiple tasks running in parallel append to a string?

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!

Upvotes: 0

Views: 389

Answers (1)

TheGeneral
TheGeneral

Reputation: 81563

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));

Upvotes: 4

Related Questions