TPL Performance Improvements in .NET 4.5
Task.WaitAll and Task.WaitAny
Task’s waiting logic in .NET 4.5 has been changed. The performance gain for this change is most apparent when waiting on multiple Tasks, such as when using Task.WaitAll and Task.WaitAny.
Let’s explore the extent of this performance boost with this benchmark code for Task.WaitAll:
public static Tuple TestWaitAll(int ntasks) { Task[] tasks = new Task[ntasks]; Action action = () => { }; for (int i = 0; i < ntasks; i++) tasks[i] = new Task(action); Stopwatch sw = new Stopwatch(); long startBytes = GC.GetTotalMemory(true); sw.Start(); Task.WaitAll(tasks, 1); sw.Stop(); long endBytes = GC.GetTotalMemory(true); GC.KeepAlive(tasks); return Tuple.Create(sw.ElapsedMilliseconds, endBytes - startBytes); }
The code above times the overhead of setting up a WaitAll for ntasks uncompleted Tasks, plus a one millisecond timeout. This test is admittedly less than perfectly precise, as the actual time before the WaitAll call times out could be anywhere from 1 millisecond to the scheduler quantum of the underlying operating system. Nevertheless, the test results still shed some light on the performance differences between .NET 4 and .NET 4.5 for this scenario: