如何确保在 windows 服务停止或关闭时完成小型 UnitOfWork 作业
How to ensure a small UnitOfWork job is completed on a windows service Stop or Shutdown
我有一份工作 运行 每 X 秒执行一次,执行时间不长(少于 5 秒),即 运行 在 Windows 服务中。我的目标是确保如果 Windows 服务在执行过程中停止,当前 运行ning 作业将完成它的执行。
这个帖子看起来很有趣,但目前还行不通:
Task Handling on Application Shutdown
我们将不胜感激。
Windows服务实现:
public partial class WindowsService : ServiceBase
{
private readonly ILogger logger;
private readonly IStartJob startJob;
private readonly CancellationTokenSource cancellationTokenSource;
private Task task;
public WindowsService(IStartJob startJob, ILogger logger)
{
// Dependancy injection of logger and JobStarter
this.startJob = startJob;
this.logger = logger;
InitializeComponent();
cancellationTokenSource = new CancellationTokenSource();
}
protected override void OnStart(string[] args)
{
task = new Task(() => startJob.Start(cancellationTokenSource.Token),
cancellationTokenSource.Token, TaskCreationOptions.LongRunning);
task.Start();
logger.Info("Service started");
}
protected override void OnStop()
{
RequestAdditionalTime(TimeSpan.FromSeconds(30).Milliseconds);
cancellationTokenSource.Cancel();
try { task.Wait(); }
catch (Exception ex) { logger.Error("Error while stopping the Service", ex); }
logger.Info("Service stopped");
}
}
StartJob 实施:
public class StartJob : IStartJob
{
private readonly ILogger logger;
private readonly IExecuteJob executeJob;
private DateTime lastExecution = DateTime.UtcNow.AddDays(-1);
public StartJob(ILogger logger, IExecuteJob executeJob)
{
this.logger = logger;
this.executeJob = executeJob;
}
public async void Start(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
var nextExecution = lastExecution.AddSeconds(5);
if (nextExecution < DateTime.UtcNow)
{
try
{
logger.Info("Start Job Execution");
// To similate long process not ended, break point here
// and stop the service before continuing the execution.
Thread.Sleep(5000);
executeJob.Execute();
logger.Info("Job completed");
AdjustLastExecution(nextExecution);
}
catch (Exception ex)
{
logger.Error("Unexpected exception while executing job", ex);
}
}
// Would expect the cancelToken to activate here or in the while condition
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
}
private void AdjustLastExecution(DateTime nextExecution)
{
// To ensure we have an heartbeat close to 5 seconds
lastExecution = nextExecution.AddSeconds(5) > DateTime.UtcNow ?
nextExecution : DateTime.UtcNow.AddSeconds(-5);
}
}
我在入口任务、任务等待和等待毫秒超时中尝试了 cancelToken 的一系列变体,但到目前为止没有任何效果。
我将我的解决方案附加到正在执行的 Windows 服务,并确保正在执行的作业将在其中间断点和 Thread.Sleep。但是 Job completed log 没有被写入并且附加的处理被丢弃在它之前。
我很快看了你的代码,我唯一想尝试的是
替换:
async void
和
async Task
我不保证它适用于你的情况,但我记得读过这篇建议避免 async void.
的文章
In C#, async void methods are a scourge upon your code..
Haacked.com | Avoid async void methods
编辑:
task = new Task(() => startJob.Start(cancellationTokenSource.Token),
cancellationTokenSource.Token, TaskCreationOptions.LongRunning);
和
task = startJob.Start(cancellationTokenSource.Token);
我有一份工作 运行 每 X 秒执行一次,执行时间不长(少于 5 秒),即 运行 在 Windows 服务中。我的目标是确保如果 Windows 服务在执行过程中停止,当前 运行ning 作业将完成它的执行。
这个帖子看起来很有趣,但目前还行不通: Task Handling on Application Shutdown
我们将不胜感激。
Windows服务实现:
public partial class WindowsService : ServiceBase
{
private readonly ILogger logger;
private readonly IStartJob startJob;
private readonly CancellationTokenSource cancellationTokenSource;
private Task task;
public WindowsService(IStartJob startJob, ILogger logger)
{
// Dependancy injection of logger and JobStarter
this.startJob = startJob;
this.logger = logger;
InitializeComponent();
cancellationTokenSource = new CancellationTokenSource();
}
protected override void OnStart(string[] args)
{
task = new Task(() => startJob.Start(cancellationTokenSource.Token),
cancellationTokenSource.Token, TaskCreationOptions.LongRunning);
task.Start();
logger.Info("Service started");
}
protected override void OnStop()
{
RequestAdditionalTime(TimeSpan.FromSeconds(30).Milliseconds);
cancellationTokenSource.Cancel();
try { task.Wait(); }
catch (Exception ex) { logger.Error("Error while stopping the Service", ex); }
logger.Info("Service stopped");
}
}
StartJob 实施:
public class StartJob : IStartJob
{
private readonly ILogger logger;
private readonly IExecuteJob executeJob;
private DateTime lastExecution = DateTime.UtcNow.AddDays(-1);
public StartJob(ILogger logger, IExecuteJob executeJob)
{
this.logger = logger;
this.executeJob = executeJob;
}
public async void Start(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
var nextExecution = lastExecution.AddSeconds(5);
if (nextExecution < DateTime.UtcNow)
{
try
{
logger.Info("Start Job Execution");
// To similate long process not ended, break point here
// and stop the service before continuing the execution.
Thread.Sleep(5000);
executeJob.Execute();
logger.Info("Job completed");
AdjustLastExecution(nextExecution);
}
catch (Exception ex)
{
logger.Error("Unexpected exception while executing job", ex);
}
}
// Would expect the cancelToken to activate here or in the while condition
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
}
private void AdjustLastExecution(DateTime nextExecution)
{
// To ensure we have an heartbeat close to 5 seconds
lastExecution = nextExecution.AddSeconds(5) > DateTime.UtcNow ?
nextExecution : DateTime.UtcNow.AddSeconds(-5);
}
}
我在入口任务、任务等待和等待毫秒超时中尝试了 cancelToken 的一系列变体,但到目前为止没有任何效果。
我将我的解决方案附加到正在执行的 Windows 服务,并确保正在执行的作业将在其中间断点和 Thread.Sleep。但是 Job completed log 没有被写入并且附加的处理被丢弃在它之前。
我很快看了你的代码,我唯一想尝试的是
替换:
async void
和
async Task
我不保证它适用于你的情况,但我记得读过这篇建议避免 async void.
的文章In C#, async void methods are a scourge upon your code..
Haacked.com | Avoid async void methods
编辑:
task = new Task(() => startJob.Start(cancellationTokenSource.Token),
cancellationTokenSource.Token, TaskCreationOptions.LongRunning);
和
task = startJob.Start(cancellationTokenSource.Token);