gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:26:09 24 4
gpt4 key购买 nike

.NET Core (2, 3) Task.Delay() 消耗四核处理器的 55%。我不明白这是否正常。如果不正常,去哪里找原因。测试代码:

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

最佳答案

你没有拖延,你需要等待那个电话。

尝试添加一些 Console.WriteLine,您会发现您的代码不会在延迟中等待。这是另一个使用异步和等待的版本。这个等待:

    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");
}
}
}

在线试用:https://dotnetfiddle.net/sCT80H

关于c# - .NET Core Task.Delay() 消耗处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com