gpt4 book ai didi

c# - 如何确保在 Windows 服务停止或关闭时完成一个小的 UnitOfWork 作业

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:06 24 4
gpt4 key购买 nike

我有一个工作,每 X 秒运行一次,执行时间不应该太长(少于 5 秒),它在 Windows 服务中运行。我的目标是确保如果 Windows 服务在执行过程中停止,当前正在运行的作业将完成它的执行。

这个线程看起来很有趣,但目前还行不通: Task Handling on Application Shutdown

我们将不胜感激。

WindowsService 实现:

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 的一系列变体,但到目前为止没有任何效果。

我将我的解决方案附加到正在执行的 WindowsService 并确保正在执行的作业将在其中间断点和 Thread.Sleep。但是 Job completed log 没有被写入,附加的 processed 被丢弃在它之前。

最佳答案

我很快看了你的代码,我唯一想尝试的是

替换:

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);

关于c# - 如何确保在 Windows 服务停止或关闭时完成一个小的 UnitOfWork 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com