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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.