Asynchronous programming
.NET .NET Core C# LINQ Visual Studio

How to use Task.WhenEach for Thread Synchronization in .NET 9.0

Welcome to today’s post.

In today’s post I will be showing how to use the Task.WhenEach() method, which is part of the System.Threading.Tasks namespace and a new inclusion to the .NET 9.0 framework.  

I will also be explaining why the new method has been introduced by showing a limitation from the use of an existing method, that uses the Task.WaitAny() method.

After I have demonstrated use of the existing approach, I will show how the new method is used. I will then compare the size of code used within each approach, then show the outputs from both approaches. 

In the first section, I will explain the original approach using the Task.WaitAny() method.

The Task.WaitAny() Approach

The Task.WaitAny() method, which is part of the System.Threading.Tasks namespace is part of a suite of useful static methods within the Task class that helps with the synchronization of running tasks as threads, and helps obtain the results and status of running tasks.

The synchronization operations can include waiting for a single task, all tasks, or any tasks (arrays of tasks), then reading off the status(es) or result(s).

The Task.WaitAny() method takes an input which is an array of Task objects, then runs the tasks within a thread until the first task in the array reaches completion. The method then returns an integer result which is the zero-based index of the Task object within the array that reaches completion with a RanToCompletion status.

When the task synchronization ends, one of the tasks completes, with the remaining tasks still running. To track the completion of the remaining tasks, you will need to re-run the Task.WaitAny() method again with the remaining tasks. This process is shown in the diagram below:

If none of the tasks in the array can be completed, then the method returns a value of -1, which usually indicates that the method has reached a timeout. The overload of the method that takes a timeout parameter (in milliseconds) can be beneficial when we create tasks that do not return for a very long time and have no definite timespan.

In the code sample below, I create three Task objects that run with increasing durations of 1100ms, 2100ms and 3100ms.

Task[] tasks = new Task[3];
for (int i = 0; i <= 2; i++)
{
    tasks[i] = Task.Run(() => Thread.Sleep((i+1) * 1000 + 100));
}

We then run a loop with the Task.WaitAny() method that, for each iteration, waits for one task to complete at a time, then reports the status of the tasks. The loop ends when all the tasks have reached a completion state or the maximum time (the timeout) for the wait is reached.

int tasksRemaining = 3;
int maximumtime = 30000;

while (tasksRemaining > 0)
{
    int index = Task.WaitAny(tasks, maximumtime);
                
    if (index == -1)
    {
        Console.WriteLine("Wait completed due to Timeout.");
        break;
    }

    Console.WriteLine("Wait completed due to Task {0} completion.", tasks[index].Id);
    Console.WriteLine("\nCurrent Status of Tasks:");
                
    foreach (var t in tasks)
    {
        Console.WriteLine("   Task {0}: {1}", t.Id, t.Status);
    }

    tasks = tasks.Where(x => x.Id != tasks[index].Id).ToArray();

    tasksRemaining -= 1;
}

Note that if we had not included the following line after the status loop:

tasks = tasks.Where(x => x.Id != tasks[index].Id).ToArray();

The above removes the latest completed task from the running task array, then we would end up with the following outputs that display the same task status for all three tasks in each loop as shown:

We can also see that Task 15 is not reported as completed!

By repeatedly calling the same Task.WaitAny() call with the same tasks, we are re-reporting the status of the same completed tasks.

When the tasks array is resized with the removal of the completed task, the resulting status outputs are as shown:

You can notice from the above that the running task status is more accurate.

When we ran the above commands, in the debugger, each item in the array of Task objects is placed in a WaitingToRun status as shown:

In addition, each Task object has an identifier, Id which we used to locate and then remove from the Task array:

When the Task.WaitAny() method executes, the status of executing tasks in the array change to a Running status as shown:

Below is the status of a task that is still running:

When a task completes, its status changes to a RanToCompletion status as shown:

When all task executions are completed, they will all be in the RanToCompletion status:

In the next section, I will show how to achieve the same outcome with the Task.WhenEach() method. 

The Task.WhenEach() Approach

In this section, I will be showing how to use the newer Task.WhenEach() method to synchronize the completion of tasks within the array.

As we saw in the previous section, we had to run the Task.WaitAny() method for each task that we wanted to wait for completion. In the above example, we created and executed three task threads, which required us to call the method three times to obtain the index of the next completed task.

That approach does work however it is inefficient in terms of code and so requires a larger implementation to achieve the outcome of waiting for each of the tasks to complete, then to report on the completion and task status.

With Task.WhenEach(), the tasks run asynchronously in their context, blocking the current thread until the next task in the array reaches completion. When a task completes, it falls into the loop body, where you can then determine its status. The remaining tasks keep running within their contexts until the second task completes. This continues until all tasks complete and are released by the synchronization. At this point, the asynchronous loop ends. This process is shown in the diagram below:

The beauty with this approach is that we don’t have to re-run the synchronization to execute all the tasks and implement all the associated code to keep track of completed tasks.

The Task.WhenEach() method I defined as shown:

public static IAsyncEnumerable<Task> WhenEach(params Task[] tasks)

The IAsyncEnumerable<Task> result allows us to run an await foreach iteration on the returned result.

Below is the code that sets up the three tasks, then runs an asynchronous await loop on each Task object that is returned from the Task.WhenEach() method:

Task[] tasks2 = new Task[3];
for (int i = 0; i <= 2; i++)
{
    tasks2[i] = Task.Run(() => Thread.Sleep(i * 1000 + 100));
}

await foreach (Task t in Task.WhenEach(tasks2))
{
    Console.WriteLine("   Task {0}: {1}", t.Id, t.Status);
}

When the above code runs and we check the state of task2 in a debug snapshot, all tasks are in a WaitingToRun state as shown:

When the first task has completed, its status is set to RanToCompletion, with the remaining tasks still in the Running state:

Eventually, all tasks will reach completion status as shown in the console output:

What we have seen from the improved method of task synchronization is that the status of each of the tasks is confined to the context of the asynchronous loop and the Task.WhenEach() method, which keeps track of the state of each task.

In the final section, I will provide the source of the above discussion.

Source Code for Both Approaches

Below is sample code of the main method that provides a basic console menu to action the task demos:

static void Main(string[] args)
{
    bool isFinished = false;

    while (!isFinished)
    {
        ConsoleKeyInfo consoleKeyInfo;

        Console.WriteLine(".NET 9 Features Demo Menu");
        Console.WriteLine("-------------------------");
        Console.WriteLine();
        Console.WriteLine("Press T for .NET 9 Task Library Demo.");
        Console.WriteLine("Press Escape to finish.");
        Console.WriteLine();

        consoleKeyInfo = Console.ReadKey(true);
        if (consoleKeyInfo.Key == ConsoleKey.Escape)
        {
            Console.WriteLine("Escape Key Pressed.");
            isFinished = true;
        }

        if (consoleKeyInfo.Key == ConsoleKey.T)
        {
            Task task = DotNet9TaskDemos();
            Task.WaitAny(task);
        }
        Console.WriteLine();
    }
}

Below is the method the demonstrates both task synchronization approaches:

private static async Task DotNet9TaskDemos()
{
    Console.WriteLine("Test Task.WaitAny()");
    Console.WriteLine();

    Task[] tasks = new Task[3];
    for (int i = 0; i <= 2; i++)
    {
        tasks[i] = Task.Run(() => Thread.Sleep((i+1) * 1000 + 100));
    }

    int tasksRemaining = 3;
    int maximumtime = 30000;

    while (tasksRemaining > 0)
    {
        int index = Task.WaitAny(tasks, maximumtime);
        Console.WriteLine("Wait completed due to Task {0} completion.",
            tasks[index].Id);
        Console.WriteLine("\nCurrent Status of Tasks:");
                
        foreach (var t in tasks)
        {
            Console.WriteLine("   Task {0}: {1}", t.Id, t.Status);
        }
        tasks = tasks.Where(x => x.Id != tasks[index].Id).ToArray();

        tasksRemaining -= 1;
    }

    Console.WriteLine();

    Console.WriteLine("Test Task.WhenEach()");
    Console.WriteLine();

    Task[] tasks2 = new Task[3];
    for (int i = 0; i <= 2; i++)
    {
        tasks2[i] = Task.Run(() => Thread.Sleep((i+1) * 1000 + 100));
    }

    await foreach (Task t in Task.WhenEach(tasks2))
    {
        Console.WriteLine("   Task {0}: {1}", t.Id, t.Status);
    }
}

When the above is executed in one run, we will see console outputs like those below (the task identifiers may vary):

In the above overview, I have compared the approaches for parallel task synchronization with the Task.WaitAny() and Task.WhenEach() methods, explaining how the latter method, which was introduced in .NET 9.0 framework improves task synchronization with code minimization.

That is all for today’s post.

I hope that you have found this post useful and informative.

Social media & sharing icons powered by UltimatelySocial