0

经过多次测试和实施来自不同文档和博客文章的关于 .NET Worker Service 的建议后,我无法阻止它在运行似乎正好 1 小时后停止。

我可以看到工作人员完成了,因为它正在生成日志,当它停止时,任务管理器中的工作进程就消失了。

这个 Worker Service 是使用 .NET 6 创建的,输出类型是 WinExe,它在 Windows 11 机器上运行。

工作人员所做的是监视机器上运行的进程,如果特定进程停止,它会重新启动它。

我想我现在的问题是:

  • 为什么它会停止(显然在 60 分钟后)?
  • 什么取消它?
  • 如何预防?
  • 它是否必须变成 Windows 服务(https://docs.microsoft.com/en-us/dotnet/core/extensions/windows-service
    • 如果是,为什么?

这些是我研究过的一些资源,但对解决问题没有帮助:

Worker 服务意外停止工作

https://blog.stephencleary.com/2020/05/backgroundservice-gotcha-silent-failure.html

这是 ExecuteAsync 方法(有一些编辑):

[SupportedOSPlatform("windows")]
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    try
    {
        if (!_isInitialSetup)
        {
            _logger.LogInformation($"Starting with account '{WindowsIdentity.GetCurrent().Name}'");
        }
    }
    catch (SecurityException)
    {
        _logger.LogError("A security exception occurred when attempting to get the account name used by the worker service.");
    }

    RunSomeActionBeforeLongRunningTask();

    try
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Run(() => { ActionToRunInTheBackground(); });
            await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
        }
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error in ExecuteAsync");
    }
    finally
    {
        // cleanup...;
    }
}

这是.csproj指定输出类型的文件的一部分:

  <PropertyGroup>
      <TargetFramework>net6.0-windows</TargetFramework>
      <Nullable>enable</Nullable>
      <ImplicitUsings>enable</ImplicitUsings>
      <OutputType>WinExe</OutputType>
      <PublishReadyToRun>true</PublishReadyToRun>
      <PublishSingleFile>true</PublishSingleFile>
      <SelfContained>true</SelfContained>
      <RuntimeIdentifier>win-x64</RuntimeIdentifier>
      <PublishTrimmed>true</PublishTrimmed>
      <BuiltInComInteropSupport>true</BuiltInComInteropSupport>

这几乎就是这个应用程序的全部内容。它运行得很好,直到它静默退出。

PS:我现在正在使用的解决方法是在进程运行大约 50 分钟后让工作人员自行重启。这一直有效,但我真的很想了解它为什么退出。

此外,我有点愿意切换到 Windows 服务,但我还没有找到任何解释为什么需要这样做。虽然,我也有兴趣用 MSIX 替换 Wix 安装程序,但我在文档中读到后者不支持 Windows 服务,所以我更愿意将服务保留为控制台 WinExe 进程。

4

0 回答 0