简体   繁体   English

在后台服务中使用 Thread.Sleep 时为真或为真时

[英]While true or while true with Thread.Sleep in a background service

I'm creating a background service that needs to run each x seconds.我正在创建一个需要每 x 秒运行一次的后台服务。 It has to be in .net Framework as the client does not want to upgrade to core or install anything on the machine other than this app.它必须在 .net 框架中,因为客户端不想升级到核心或在机器上安装除此应用程序以外的任何东西。 So I am restricted to using the Windows Service所以我只能使用 Windows 服务

My main issue is that I'm going in a while(true) loop that checks for the passed time (yes, I know I could use a timer) and I'm not sure if I should add a thread.我的主要问题是我要进入一个 while(true) 循环来检查经过的时间(是的,我知道我可以使用计时器)并且我不确定是否应该添加一个线程。 Sleep in the loop or just leave the while(true).睡在循环中或只是离开 while(true)。 My main concern is not to overload the CPU/memory.我主要关心的是不要让 CPU/内存过载。

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

while (true)
{
    if (nextIteration < DateTime.Now)
    {
        RunService();
        nextIteration = DateTime.Now.Add(TimeSpan.FromSeconds(timer));
    }
}

If you are implementing a service of type BackgroundService you should consider using the CancellationToken in your while:如果您正在实施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
        }          
    }
}

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

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

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