简体   繁体   English

C# - 多个任务可以并行运行 append 到一个字符串吗?

[英]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.为了加快速度,我一次启动多个 API 请求,而不是一次等待一个。 Open to other options/solutions.打开其他选项/解决方案。

Thanks!谢谢!

I'd suggest creating the tasks then await ing them all with Task.WhenAll then use string.Join我建议创建任务,然后使用string.Join将它们全部await ,然后使用Task.WhenAll

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.如果没有任务出错并且没有任务被取消,则生成的任务将在 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返回任务的 Result 将设置为一个数组,其中包含所提供任务的所有结果,其顺序与提供的顺序相同

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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