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?
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:
StringBuilder
is not thread-safe: Is .NET's StringBuilder thread-safe
==> you should lock
inside the ContinueWith
As pointed out by Matías: You should also check for a successful task completion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With