【发布时间】:2020-04-20 09:20:38
【问题描述】:
我有一个 Windows 服务,它通过每秒运行几个测试来监控我的应用程序。已经提交了一个错误报告,说服务在一段时间后停止运行,我正在尝试找出原因。
我怀疑下面的代码是罪魁祸首,但我无法准确理解它是如何工作的。 ContinueWith语句最近被注释掉了,不知道是不是需要
private Task CreateTask(Action action)
{
var ct = _cts.Token;
return Task.Run(async () =>
{
ct.ThrowIfCancellationRequested();
var sw = new Stopwatch();
while (true)
{
sw.Restart();
action();
if (ct.IsCancellationRequested)
{
_logger.Debug("Cancellation requested");
break;
}
var wait = _settings.loopStepFrequency - sw.ElapsedMilliseconds;
if (wait <= 0) // No need to delay
continue;
// If ContinueWith is needed wrap this in an ugly try/catch
// handling the exception
await Task.Delay(
(int)(_settings.loopStepFrequency - sw.ElapsedMilliseconds),
ct); //.ContinueWith(tsk => { }, ct);
}
_logger.Debug("Task was cancelled");
}, _cts.Token);
}
这段代码有什么明显的问题吗?
【问题讨论】:
-
您可能希望使用
System.Timers.Timer来安排测试。如果您的_cts在Task.Delay中被取消,您将收到异常,因此您可能需要为此使用 try-catch。 -
为什么您认为这与服务停止问题有关?
标签: c# async-await windows-services topshelf