【发布时间】:2017-12-14 05:56:23
【问题描述】:
以下是在 Asp.Net Core 中实现长时间运行的后台工作的正确模式吗?还是我应该使用某种形式的Task.Run/TaskFactory.StartNew 和TaskCreationOptions.LongRunning 选项?
public void Configure(IApplicationLifetime lifetime)
{
lifetime.ApplicationStarted.Register(() =>
{
// not awaiting the 'promise task' here
var t = DoWorkAsync(lifetime.ApplicationStopping);
lifetime.ApplicationStopped.Register(() =>
{
try
{
// give extra time to complete before shutting down
t.Wait(TimeSpan.FromSeconds(10));
}
catch (Exception)
{
// ignore
}
});
});
}
async Task DoWorkAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await // async method
}
}
【问题讨论】:
-
您可以使用像
Hangfire这样的库来执行此操作。 -
有关 IApplicationLifetime 的更多详细信息请参阅khalidabuhakmeh.com/…
标签: c# asp.net-core .net-core