1053 使用 .NET Core 3.1 Worker Service 时出现 Windows 服务错误

问题描述 投票:0回答:4

我创建了一个工作服务,它可以在 Visual Studio 2019 中的调试和发布中按预期工作。该服务监视要创建的 .csv,并使用正确的编码 (UTF-8) 将其重写到另一个目录。当我发布它并创建 Windows 服务时,在启动 Windows 服务时我收到

Error 1053: The service did not respond to the start or control request in a timely fashion
。据我了解,我的
OnStart
返回得不够快。但我不确定如何调试。

节目课

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;

namespace SupplyProUTF8service
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.File(@"\\REP-APP\temp\workerservice\log.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();

            try
            {
                Log.Information("Application Started.");
                CreateHostBuilder(args).Build().Run();

            }
            catch (Exception e)
            {

                Log.Fatal(e, "Application terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }

            CreateHostBuilder(args).Build().Run();

        }


        public static IHostBuilder CreateHostBuilder(string[] args)
            => Host.CreateDefaultBuilder(args).UseWindowsService().ConfigureServices((hostContext, services)
                => { services.AddHostedService<Worker>(); }).UseSerilog();
    }
}

新工人阶级 仍然出现 1053 错误

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace SupplyProUTF8service
{
    public class Worker : BackgroundService
    {

        private readonly string ordrstkPath;
        private readonly string conrstkPath;
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            ordrstkPath = @"\\Rep-app\sftp_root\supplypro\ordrstk";
            conrstkPath = @"\\Rep-app\sftp_root\supplypro\Conrstk";
            _logger = logger;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {

            _logger.LogInformation("SupplyProRewrite Service started");
            return base.StartAsync(cancellationToken);
        }


        private FileSystemWatcher Watch(string path)
        {
            //initialize
            FileSystemWatcher watcher = new FileSystemWatcher
            {

                //assign paramater path
                Path = path,

                //don't watch subdirectories
                IncludeSubdirectories = false
            };

            //file created event
            watcher.Created += FileSystemWatcher_Created;

            //filters
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.Attributes;

            //only look for csv
            watcher.Filter = "*.csv";

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            return watcher;
        }
        private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {
            _logger.LogInformation("{FullPath} has been created", e.FullPath);
            Thread.Sleep(10000);
            while (!IsFileLocked(e.FullPath))
            {
                ReadWriteStream(e.FullPath, e.Name);
                break;
            }
        }

        private static bool IsFileLocked(string filePath)
        {
            try
            {
                using FileStream originalFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                originalFileStream.Close();
            }
            catch (Exception)
            {
                return true;
            }
            return false;
        }

        private void ReadWriteStream(string path, string fileName)
        {

            string originalPath = path;
            //destination path by replacing SFTP user directory
            string destinationPath = path.Replace(@"\supplypro\", @"\ftpuser\");

            string currentLine;

            using FileStream originalFileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            using FileStream destinationFileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);
            using StreamReader streamReader = new StreamReader(originalFileStream);
            using StreamWriter streamWriter = new StreamWriter(destinationFileStream);
            try
            {
                currentLine = streamReader.ReadLine();
                while (currentLine != null)
                {

                    streamWriter.WriteLine(currentLine);
                    currentLine = streamReader.ReadLine();

                }

                streamReader.Close();
                streamWriter.Close();

                //archive path
                string archivePath = path.Replace(fileName, @"archive\" + fileName);

                //move to archive path
                while (!IsFileLocked(originalPath))
                {
                    try
                    {
                        File.Move(originalPath, archivePath, true);
                        _logger.LogInformation("{FileName} moved to archive", fileName);
                        break;
                    }
                    catch (Exception e)
                    {
                        _logger.LogError("Unable to move {fileName} to archive", fileName, e);
                        break;
                    }
                }


            }
            catch (Exception e)
            {
                //error path
                string errorPath = path.Replace(fileName, @"error\" + fileName);

                //move to error path
                while (!IsFileLocked(originalPath))
                {
                    File.Move(path, errorPath);
                    _logger.LogError("{FullPath} file was moved to error", originalPath, e);
                    break;
                }

            }
            finally
            {
                destinationFileStream.Close();
                originalFileStream.Close();

            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using (Watch(ordrstkPath))
            {
                _logger.LogInformation("ordrstk being watched");
                await Task.Delay(Timeout.Infinite, stoppingToken);
            }

            using(Watch(conrstkPath))
            {
                _logger.LogInformation("conrstk being watched");
                await Task.Delay(Timeout.Infinite, stoppingToken);
            }
        }
    }
}
c# .net-core
4个回答
5
投票

我不知道为什么我一开始不这样做。我对那些花时间看这个的人表示歉意。我最终在 Powershell 中使用

.\WorkerService.exe
运行了该应用程序。这引发了我缺少 ASP.net Core 运行时的错误。我之前安装了 .NET core 的运行时,最近安装了 5.0。此辅助服务必须需要具有托管运行时的特定 ASP.Net Core:下载。服务现在开始没有问题。


5
投票

Windows 11 计算机上的 Dot Net core 6 服务项目(来自 Visual Studio 2022 的默认项目模板)也发生了同样的问题。 在主机声明后使用

UseWindowsService()

//Program.cs

IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
    services.AddHostedService<Worker>();
}).UseWindowsService()
.Build();

await host.RunAsync();

注意: 使用时需要

nuget
套件参考
Microsoft.Extensions.Hosting.WindowsServices
UseWindowsService()


1
投票

由于

FileSystemWatcher
不是
async
关键字意义上的异步,而是
IDisposable
,因此您的
ExecuteAsync
可能如下所示:

protected override async Task ExecuteAsync(CancellationToken cancel)
{
    using (/* method that sets up and returns your watcher */)
    {
        await Task.Delay(Timeout.Infinite, cancel);
    }
}

此处未显示,但您可能希望在服务关闭时捕捉

TaskCanceledException
抛出的
Task.Delay


0
投票

使用UseWindowsService()修复了

错误1053
,感谢您的推荐。

我在

NET core 3
中看到不是那样的。

using WindowsService;

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    }).UseWindowsService ()
    .Build();

host.Run();
© www.soinside.com 2019 - 2024. All rights reserved.