Search code examples
c#.net-coreparallel-processingsimultaneous

Execute tasks simultaneously in parallel in C# .NET 5


I am trying to execute an array of tasks at exactly the same time, to the nanosecond. Is this possible?

It seems like the more tasks I add, the greater the range of inaccuracy - which leads me to believe I am doing something wrong.

Is there a best practice for this?

Here is my code with the results I am getting:

class Program
{
    static async Task Main(string[] args)
    {
        int[] iterations = Enumerable.Range(1, 100).ToArray();
        Func<Task<DateTime>>[] delegates = new Func<Task<DateTime>>[iterations.Length];

        foreach (int i in iterations)
        {
            async Task<DateTime> GetTime()
            {
                await Task.Delay(1000);
                return DateTime.Now;
            }

            delegates[Array.IndexOf(iterations, i)] = GetTime;
        }

        Task<DateTime>[] tasks = delegates
            .AsParallel()
            .Select(async task => await task())
            .ToArray();

        await Task.WhenAll(tasks);

        DateTime[] dateTimes = tasks
            .Select(l => l.Result)
            .ToArray();

        foreach (DateTime dateTime in dateTimes)
            Console.WriteLine(dateTime.ToString("yyyy-MM-dd HH:mm:ss.ffffff"));
        Console.WriteLine("Range: " + (dateTimes.Max() - dateTimes.Min()).TotalMilliseconds);

        Console.ReadKey();
    }
}

My average result for 100 iterations:

Range: 7.6709


Solution

  • I am trying to execute an array of tasks at exactly the same time, to the nanosecond. Is this possible?

    No. This is not possible on any operating system that uses preemptive scheduling, such as Windows or Linux.