简体   繁体   中英

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!

I'd suggest creating the tasks then await ing 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM