【发布时间】:2018-12-05 17:06:27
【问题描述】:
我正在尝试在 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>();
【问题讨论】:
-
这行得通吗? services.AddHostedService
();将其添加为瞬态,这会在 ExecuteAsync 返回后不久破坏 FSWImpl 和 FileSystemWatcher 对象。因此,该文件将不再被观看。
标签: asp.net-core filesystemwatcher asp.net-core-2.1