我正在尝试在AspNet Core 2.1应用程序中使用BackgroundService
的实现。 在ExecuteAsync
中创建了一个FileSystemWatcher,并链接了关联事件,但是,fsw事件要么从未触发(无法访问?已处理?)要么是由于异步或范围混乱而出现了某些问题。 我似乎想不出解决方法。以下是相关代码。
public class FSWImpl : BackgroundService
{
private readonly IHostingEnvironment _env;
private readonly ILogger<LiftAndShift> _logger;
private FileSystemWatcher _fsw;
public LiftAndShift(IHostingEnvironment env, ILogger<FSWImpl> logger)
{
_env = env;
_logger = logger;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Creating new FSW");
var path = Path.Combine(_env.ContentRootPath, "WebData");
_fsw = new FileSystemWatcher(path,"*.json");
_fsw.Created += _fsw_Created;
_fsw.Changed += _fsw_Changed;
_fsw.Renamed += _fsw_Renamed;
_fsw.Error += _fsw_Error;
return Task.CompletedTask;
}
private void _fsw_Error(object sender, ErrorEventArgs e) => _logger.LogInformation("File error");
private void _fsw_Renamed(object sender, RenamedEventArgs e) => _logger.LogInformation("File Renamed");
private void _fsw_Changed(object sender, FileSystemEventArgs e) => _logger.LogInformation("File changed");
private void _fsw_Created(object sender, FileSystemEventArgs e) => _logger.LogInformation("File created");
}
我在启动时将此服务注册为 services.AddHostedService<FSWImpl>();