我知道服务控制的恢复部分,以及我们如何设置一个应用程序在失败后重新启动。
我已经创建了一个.NET 6工作人员服务,作为一个窗口服务运行。问题是,每当代码中出现异常时,应用程序就会记录错误,然后优雅地关闭。这并不表示服务应该重新启动,因为它返回的退出代码为0。
我尝试返回一个退出代码-1 (通过设置Environment.ExitCode并从Main()返回-1 ),但是它被忽略了。
我还尝试过设置底层WindowsServiceLifetime的退出代码,但这也不起作用。
有没有任何方法让SCM重新启动服务,无论它如何关闭?
发布于 2022-01-06 08:47:42
异常不应使主机崩溃。异常不会影响IIS,也不应破坏Windows服务。
您应该将try/catch放在工作开始的地方--每个端点和后台服务。在捕获中,您应该记录错误。
下面是一个端点示例:
[Route("Get")]
[HttpGet]
public async Task<IActionResult> GetAsync()
{
try
{
return Ok(await BusinessRules.GetSomethingAsync());
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
throw;
}
}下面是一个后台服务示例:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
//Need a try/catch round Task.Delay because exception will the thrown
//if stoppingToken is activated and we don't care about logging this exception.
try
{
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
catch { }
await BusinessRules.DoSomethingAsync(stoppingToken);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
//In a loop, log file can fill up quickly unless we slow it down after error.
try
{
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
catch { }
}
}
}https://stackoverflow.com/questions/70600986
复制相似问题