user1787509
user1787509

Reputation:

.NET Core Task.Delay() consume processor

.NET Core (2, 3) Task.Delay() consume 55% of the quad-core processor. I don’t understand whether this is normal or not. And if it’s not normal, where to look for the reason. Test code:

using System.Threading.Tasks;
class Program
{
    static void Main(string[] args)
    {
        while (true)
            Task.Delay(1000);
    }
}

Upvotes: 2

Views: 1223

Answers (1)

Carlos Garcia
Carlos Garcia

Reputation: 2970

You are not delaying, you need to await that call.

Try adding some Console.WriteLine and you will see that your code does not wait in the delay. Here another version using async and await. This one waits:

    using System;
    using System.Threading.Tasks;
    class Program
    {
        static async Task Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("starting the loop");
                
                Task.Delay(1000);
                Console.WriteLine("this is printed inmediately, previous delay does not stop the execution");
                
                await Task.Delay(1000);
                Console.WriteLine("this happens 1 second later, the previous delay is awaited");
            }
        }
    }

Try it online: https://dotnetfiddle.net/sCT80H

Upvotes: 12

Related Questions