简体   繁体   English

.NET Core Task.Delay() 消耗处理器

[英].NET Core Task.Delay() consume processor

.NET Core (2, 3) Task.Delay() consume 55% of the quad-core processor. .NET Core (2, 3) Task.Delay() 消耗四核处理器的 55%。 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);
    }
}

You are not delaying, you need to await that call.你没有拖延,你需要await那个电话。

Try adding some Console.WriteLine and you will see that your code does not wait in the delay.尝试添加一些 Console.WriteLine ,您会看到您的代码不会在延迟中等待。 Here another version using async and await.这里使用 async 和 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在线试用: https://dotnetfiddle.net/sCT80H

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM