【问题标题】:Adding string to StringBuilder from async method从异步方法将字符串添加到 StringBuilder
【发布时间】:2014-09-09 11:20:42
【问题描述】:

我有一个返回字符串的异步方法(来自网络)。

async Task<string> GetMyDataAsync(int dataId);

我有:

Task<string>[] tasks = new Task<string>[max];
for (int i = 0; i < max; i++)
{
    tasks[i] = GetMyDataAsync(i);
}

如何将每个任务的结果附加到StringBuilder?

我想知道怎么做

A) 按任务创建顺序

B) 为了完成任务

我该怎么做?

【问题讨论】:

    标签: c# .net string asynchronous task


    【解决方案1】:

    A) 按任务创建顺序

    Task<string>[] tasks = new Task<string>()[max];
    for (int i = 0; i < max; i++)
    {
        tasks[i] = GetMyDataAsync(i);
    }
    Task.WaitAll(tasks);
    foreach(var task in tasks)
        stringBuilder.Append(task.Result);
    

    B) 为了完成任务

    Task<string>[] tasks = new Task<string>()[max];
    for (int i = 0; i < max; i++)
    {
        tasks[i] = GetMyDataAsync(i).ContinueWith(t => stringBuilder.Append(t.Result));
    }
    Task.WaitAll(tasks);
    

    如果您在 async 方法中,您也可以使用 await Task.WhenAll(tasks) 代替 Task.WaitAll。

    注意:

    1. StringBuilder 不是线程安全的:Is .NET's StringBuilder thread-safe ==> 你应该在lock 里面ContinueWith

    2. 正如 Matías 所指出的:您还应该检查任务是否成功完成

    【讨论】:

    • 谢谢。正是我想要的。
    猜你喜欢
    • 2021-09-04
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多