Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 11 down vote accepted

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

share|improve this answer
    
Thanks. Exactly what I was looking for. –  Hooch 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.