当工作程序是事件驱动时,BackgroundService.ExecuteAsync 应该返回什么? [英] What should BackgroundService.ExecuteAsync return when the worker is event-driven?
问题描述
工作服务是在 .NET Core 3.x 中编写 Windows 服务的新方法.worker 类扩展 Microsoft.Extensions.Hosting.BackgroundService
并实现 ExecuteAsync
.该方法的文档说:
A Worker Service is the new way to write a Windows service in .NET Core 3.x. The worker class extends Microsoft.Extensions.Hosting.BackgroundService
and implements ExecuteAsync
. The documentation for that method says:
该方法在 IHostedService 启动时调用.该实现应返回一个任务,该任务表示正在执行的长时间运行操作的生命周期.
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()
返回一些东西以防止服务关闭吗?
What should this method return when the work being done by the service is not a long-running operation in the usual sense, but event-driven? For example, I'm writing a service that sets up a FileSystemWatcher
. How would I encapsulate that in a Task
? There's no Task.Never()
, so should I just return something based on a very long Task.Delay()
to prevent the service from shutting down?
private async Task DoStuffAsync(CancellationToken cancel)
{
// register events
while(!cancel.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromDays(1000000), cancel);
}
// unregister events
}
推荐答案
您也可以使用实际的无限延迟:
You could also use an actual infinite delay:
await Task.Delay(Timeout.Infinite, cancellationToken);
这篇关于当工作程序是事件驱动时,BackgroundService.ExecuteAsync 应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!