Search code examples
c#asp.netblazorblazor-client-side

Running Tasks from List


I am trying to run a task List using the following method:

List<Task> tasks = new List<Task>();

tasks.Add(new Task(() => this.firstMethod()));
tasks.Add(new Task(() => this.secondMethod()));

However, if I use one of the two examples below I get the following issues:

foreach (Task task in tasks)
{
    await Task.Run(() => task);
}

In this first case, the tasks don't run at all.

foreach (Task task in tasks)
{
    task.Start();
    task.Wait();
}

In this second case, it runs only once, then I get the following error:

Start may not be called on a task that has completed

What am I missing?


Solution

  • You cannot re-use a Task. So let's start with creating an array of delegates

    List<Action> tasks = new List<Action>();
    
    tasks.Add(this.firstMethod);
    tasks.Add(this.secondMethod);
    

    and then run them sequentially, on additional threads (leaving the main thread free to update the UI):

    foreach (Action task in tasks)
    {
        await Task.Run(task);
    }
    

    but this loop could be done in many ways, depending on the context of the calling code and the nature of the payloads.

    This may be not the best solution.