辅助服务是在 .NET Core 3.x 中编写 Windows 服务的新方法。 worker 类(Class)延伸Microsoft.Extensions.Hosting.BackgroundService
并实现 ExecuteAsync。该方法的文档说:
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
当服务正在完成的工作不是通常意义上的长时间运行操作而是事件驱动时,此方法应该返回什么?例如,我正在编写一个设置 FileSystemWatcher
的服务。 。我如何将其封装在 Task
中?没有 Task.Never()
,那么我是否应该返回基于很长的 Task.Delay()
的内容以防止服务关闭?
private async Task DoStuffAsync(CancellationToken cancel)
{
// register events
while(!cancel.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromDays(1000000), cancel);
}
// unregister events
}
最佳答案
您还可以使用实际的无限延迟:
await Task.Delay(Timeout.Infinite, cancellationToken);
关于.net-core - 当工作线程是事件驱动时,BackgroundService.ExecuteAsync 应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196690/