Home > other >  How to make a void method inside a for loop to run in async way
How to make a void method inside a for loop to run in async way

Time:01-12

I have a for loop and inside this for loop, it has a void method which would generally take time. I want to run this void method in an async way and want to call printFinalMessage() after doStuff(ele) is completed for all the ele in list.

for (int ele in list)
{
    doStuff(ele);
}

printFinalMessage()

Would appreciate any help.

CodePudding user response:

The keyword for your question is await all tasks this is reference from microsoft, add your task to a list and await all of them. Notice that the signature of DoStuff() is Task

var list = new List<int>() { 1, 2, 3};

var taskList = new List<Task>();

foreach(var ele in list)
{
    taskList.Add(DoStuff(ele));
    //or you can write like
    //var task = DoStuff(ele); 
    //taskList.Add(task);
}

await Task.WhenAll(taskList);

public Task DoStuff(int ele){ }

CodePudding user response:

I would suggest just using a parallel.foreach loop. This will process elements concurrently, but not asynchronously. Meaning the loop will go faster, but printFinalMessage will only be printed when all items have actually completed processing:

Parallel.Foreach(list, ele => {
    doStuff(ele);
}
printFinalMessage();

You might want to also run the entire loop in a background task, so the UI does not freeze while the loop is running. See how to run a task in the background.

  • Related