.NET核心systemd守护程序中的FileSystemWatcher

时间:2020-04-23 21:36:52

标签: c# linux .net-core systemd

我有一个.NET core 3.1“工作者”服务(例如https://devblogs.microsoft.com/dotnet/net-core-and-systemd/)。

我正在使用FileSystemWatcher类来监视文件夹中的新文件并为其触发过程。该服务可以在Windows中按预期工作(作为服务并作为控制台程序运行),而在Linux中直接在终端中运行时可以运行。

将其作为守护程序(sudo systemctl start {myservice}.service)启动时,它会启动,但不会监视该文件夹。

在我的工人班下。

如果我在系统中扩展了手表的最大数量,那么它将起作用。

sudo nano /etc/sysctl.conf

fs.inotify.max_user_watches = 1048576

有什么主意,为什么我需要增加最大手表数量?。请注意,我正在监视的文件夹仅包含大约100个文件(默认文件夹为8192个最大手表)。

我担心的是,我对这门课不太了解,因此我将最高的手表数量设置为最高的数字,却不知道何时到达或为什么到达。另外,FileSystemWatcher似乎完全不知道发生了什么,因此我的程序无法执行任何操作,因为它不知道。


    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        private FileSystemWatcher _fileSystemWatcher;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Service startup.");
             fileSystemWatcher = new FileSystemWatcher(@"/myfolder/myfolder2");
            _fileSystemWatcher.IncludeSubdirectories = true;

            _fileSystemWatcher.Filter = "*.xml"; 
            _fileSystemWatcher.Created += (e, args) => _logger.LogWarning("StartAsync watcher: {0}", args.FullPath);
            _fileSystemWatcher.EnableRaisingEvents = true;

            return base.StartAsync(cancellationToken);
        }


        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping Service");

            await base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Service Execute.");
                        
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Keep alive: {time}", DateTimeOffset.Now);
                await Task.Delay(5*60*1000, stoppingToken);
            }

            _logger.LogInformation("Service Execute stopped.");
        }
}


0 个答案:

没有答案