11

I have async method that returns string (From web).

async Task<string> GetMyDataAsync(int dataId);

I have:

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

How can I append result of each of this tasks to StringBuilder?

I would like to know how to do it

A) In order of task creation

B) In order that tasks finish

How can I do it?

Hooch
  • 28,817
  • 29
  • 102
  • 161

1 Answers1

15

A) In order of task creation

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) In order that tasks finish

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

If you are inside an async method you can also use await Task.WhenAll(tasks) instead of the Task.WaitAll.

ATTENTION:

  1. StringBuilder is not thread-safe: Is .NET's StringBuilder thread-safe ==> you should lock inside the ContinueWith

  2. As pointed out by Matías: You should also check for a successful task completion

Community
  • 1
  • 1
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113