Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding string to StringBuilder from async method

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?

like image 418
Hooch Avatar asked Sep 09 '14 11:09

Hooch


1 Answers

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

like image 51
Christoph Fink Avatar answered Nov 07 '22 06:11

Christoph Fink