While true 或 while true with Thread.Sleep 在后台服务中

And*_*rei 0 .net c# background-service .net-4.8

我正在创建一个需要每 x 秒运行一次的后台服务。它必须位于 .net Framework 中,因为客户端不想升级到核心或在计算机上安装除此应用程序之外的任何内容。所以我只能使用 Windows 服务

我的主要问题是我要进入一个 while(true) 循环来检查经过的时间(是的,我知道我可以使用计时器),并且我不确定是否应该添加一个线程。在循环中休眠或只保留 while(true)。我主要关心的是不要让 CPU/内存超载。

var nextIteration = DateTime.Now.Add(TimeSpan.FromSeconds(timer * (-1)));

while (true)
{
    if (nextIteration < DateTime.Now)
    {
        RunService();
        nextIteration = DateTime.Now.Add(TimeSpan.FromSeconds(timer));
    }
}
Run Code Online (Sandbox Code Playgroud)

Rad*_*tos 6

如果您正在实现BackgroundService类型的服务,您应该考虑在以下时间使用CancellationToken :

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {    
        try
        {
             //do work
             await Task.Delay(TimeSpan.FromSeconds(x), stoppingToken);
        }
        catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
        {
            //handle cancelation requested exception
        }
        catch (Exception ex)
        {
            //handle ex
        }          
    }
}
Run Code Online (Sandbox Code Playgroud)

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

  • 捕获 TaskCancelledException 也可能有用:) (2认同)