Question not understanding async completely

sejsbo

New member
Joined
Feb 16, 2020
Messages
2
Programming Experience
1-3
Hi everyone, I have something that i simply need to get some help with.
I am doing some exercises with async and await. I have this method that i want to make asynchronous. It simply supposed to take an array of strings, and then create a List of strings with the same content, but just with something appended to every string.
C#:
private async static Task<List<string>> ParTest(string[] thisstringlist)
{
    List<string> returnList = new List<string>();           

    for (int i = 0; i < thisstringlist.Length-1; ++i)
    {
        Task.Run(() => returnList.Add(thisstringlist + "pluuus this"));
    }

    return returnList;
}
Now, I know that i need to put something as await, but I really dont know what! I simply want all the adding operations to happen on the different cores, so I know i need to do a await operation somewhere, but i really dont know what to do.
I really hope someone can help me out
 
Last edited by a moderator:
I'd probably be inclined to use Parallel.ForEach to do the actual processing. You could have a single Task.Run call and, inside that, you create the list, populate it with ForEach and then return it. You can then await that call and return the result, e.g.
C#:
private static async Task<List<string>> AppendToItems(string[] input)
{
    return await Task.Run(() =>
                          {
                              var output = new List<string>();

                              Parallel.ForEach(input, item => output.Add(item + "suffix"));

                              return output;
                          });
}
 
One point to note is that, if you add the items to the list in parallel, there's no guarantee that they will end up in the same order as they were in the array. They probably will but it's not guaranteed to be that way.
 
yes I had an idea that parralel.foreach would probably be the correct solution, I just really wanted to understand await properly.
 
If you are a visual learner, the flowchart/diagram on this article may explain how async and await work with each other.
 
Back
Top Bottom