在“System.Web”ASP.NET中,可以通过以下方式注册后台工作RegisterObject
/QueueBackgroundWorkItem
为了参与 IIS 的关闭序列(完成 90 秒的宽限期),但我正在努力寻找 ASP.NET 5 中的确切等效项。
查看源代码Microsoft.AspNet.Hosting.HostingEngine https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEngine.cs#L32,我可以看到它通过信号发出IApplicationLifecycle.ApplicationStopping
and IApplicationLifecycle.ApplicationStopped
(在其之间放置服务器和PipelineInstance
),但似乎没有任何空间需要 90 秒的宽限期RegisterObject
在旧的 API 中。
IIS 集成层尚未开源(如果有的话),因此很难了解该实现如何映射事物。
我缺少 API 吗?我应该通过以下方式执行阻塞关闭吗CancellationToken.Register()
?这是“v1 of vNext”中遗漏的东西吗?
任何启发将不胜感激。
我使用基于 Katana 的 Hangfire 实现作为灵感创建了以下内容。除了检查 IIS Express 终止时关闭代码是否运行之外,它没有进行任何测试,但它可以作为概念证明。
这里的设计很明显not对于“即发即忘”任务,因为它们可以在关闭之前触发。然而,它确实适用于幂等队列处理器之类的东西(假设空闲关闭超时已被禁用)
public static class BackgroundServiceExtensions
{
public static void UseBackgroundService(
this IApplicationBuilder builder, Func<CancellationToken, Task> service)
{
var lifetime = (IApplicationLifetime)builder.ApplicationServices
.GetService(typeof(IApplicationLifetime));
var stoppingToken = lifetime.ApplicationStopping;
var stoppedToken = lifetime.ApplicationStopped;
// This, in particular, would need to be properly thought out,
// preferably including an execution context to minimise threadpool use
// for async-heavy background services
Task serviceTask = Task.Run(() => service(stoppingToken));
stoppedToken.Register(() =>
{
try
{
// Block (with timeout) to allow graceful shutdown
if (!serviceTask.Wait(TimeSpan.FromSeconds(30)))
{
// Log: Background service didn't gracefully shutdown.
// It will be terminated with the host process
}
}
catch(Exception)
{
// Ignored
}
});
}
}
然后可以像这样使用:
app.UseBackgroundService(async cancellationToken =>
{
while (!cancellationToken.IsCancellationRequested)
{
System.Diagnostics.Debug.WriteLine("Tick...");
try
{
// Use cancellationToken for anything that is (logically) cancellable
await Task.Delay(1000, cancellationToken);
}
catch(TaskCanceledException)
{ }
}
System.Diagnostics.Debug.WriteLine("Cancellation requested, shutting down...");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)