对.net中的服务使用Task.WaitAll()的问题
本文关键字:WaitAll 问题 Task net 服务 | 更新日期: 2023-09-27 18:19:16
我有一个OnStart()方法的服务:
protected override void OnStart(string[] args)
{
this.manager.StartManager();
this.log.LogEvent(this.id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Service started"));
}
和OnStop()方法:
protected override void OnStop()
{
this.manager.CancellationTokenSource.Cancel();
this.log.LogEvent(this.id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Service stopped"));
}
StartManager()方法实现如下:
public void StartManager()
{
foreach (var reportGeneratorThread in this.ReportGenerators)
{
reportGeneratorThread.Start();
Thread.Sleep(1000);
}
try
{
Task.WaitAll(this.Tasks.ToArray());
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
var taskException = v as TaskCanceledException;
if (v != taskException)
{
foreach (var reportGenerator in this.ReportGenerators)
{
if (reportGenerator.Task.IsFaulted)
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Unhandled exception from Task " + reportGenerator.Task.Id));
ReportGeneratorThread faultedReportGeneratorThread = this.GetThreadById(reportGenerator.Task.Id);
var index = this.ReportGenerators.FindIndex(t => t.Equals(faultedReportGeneratorThread));
this.DisposeFaultedThread(faultedReportGeneratorThread, index);
this.ReportGenerators[index].Start();
this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, "Faulted Task, and instance of ReportGeneratorThread is recreated and corresponding task is started"));
break;
}
}
}
else if (taskException != null)
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Task " + taskException.Task.Id + " has thrown a Task Canceled Exception"));
}
}
}
}
问题发生在我的StartManager()方法中,因为reportGeneratorThread.Start()方法正在启动一个任务,该任务在while循环中不断生成报告,该任务只能在抛出取消令牌时中止,并且我将其抛出在我的服务OnStop()方法中。因此,当我测试我的服务时,程序无法到达Task.WaitAll()以外的地方,这阻止了我完成OnStart()方法,并且我收到以下错误:
Error 1053: the service did not respond to the start or control request in a timely fashion
我仍然需要管理我的任务,所以我实际上需要task . waitall()方法,但我也需要修复这个问题。在这种情况下,我如何完成OnStart()方法?不改变代码结构的最佳方法是什么?
添加更多代码:
这是我的任务调用的方法:
private void DoWork()
{
while (this.Running)
{
this.GenerateReport();
Thread.Sleep(Settings.Default.DefaultSleepDelay);
}
this.log.LogDebug(string.Format(CultureInfo.InvariantCulture, "Worker thread stopping."));
}
和GenerateReport()方法:如果服务请求取消,则调用Stop()方法。这个方法抛出TaskCancelledException异常。
public void GenerateReport()
{
if (this.cancellationToken.IsCancellationRequested)
{
this.Stop();
}
var didwork = false;
try
{
didwork = this.reportGenerator.GenerateReport(this.getPermission, this.TaskId);
}
catch (Exception e)
{
this.log.LogError(ReportGenerator.CorrelationIdForPickingReport, string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Error during report generation."), 0, e);
}
finally
{
if (!didwork)
{
Thread.Sleep(Settings.Default.ReportGenerationInterval);
}
}
}
如果没有一个好的,最小的, 完整的代码示例来清楚地说明你的问题,很难确切地理解代码在做什么。至少有一些我一眼就能看到的奇怪的东西:
- 你的方法旨在重新启动一个报告生成器线程。但据我所知,它只能重新启动一个。如果你以后有更多的错误,没有代码等待检测和处理它。
- 使用
WaitAll()
将阻止代码检测到甚至一个故障,直到所有任务完成。因此,它们要么都需要在重启之前出现故障,要么直到你真正停止服务并取消任务时才会检测到故障。 - 只有当
taskException
为null
时,v != taskException
才为真。所以在我看来,稍后检查它是非空的是毫无意义的。 - 我不明白在开始每个任务之间睡1秒有什么意义。
所以我不确定有可能知道修复所有这些代码的最佳方法是什么。也就是说,当前的问题似乎很清楚:您的OnStart()
方法在设计上需要及时返回,但您当前的实现无法做到这一点。这个基本问题似乎是可以解决的,通过使StartManager()
方法成为async
方法,并使用await
将控制权返回给调用者,直到发生一些有趣的事情。它可能看起来像这样:
public async Task StartManager()
{
foreach (var reportGeneratorThread in this.ReportGenerators)
{
reportGeneratorThread.Start();
Thread.Sleep(1000);
}
try
{
await Task.WhenAll(this.Tasks.ToArray());
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
var taskException = v as TaskCanceledException;
if (v != taskException)
{
foreach (var reportGenerator in this.ReportGenerators)
{
if (reportGenerator.Task.IsFaulted)
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Unhandled exception from Task " + reportGenerator.Task.Id));
ReportGeneratorThread faultedReportGeneratorThread = this.GetThreadById(reportGenerator.Task.Id);
var index = this.ReportGenerators.FindIndex(t => t.Equals(faultedReportGeneratorThread));
this.DisposeFaultedThread(faultedReportGeneratorThread, index);
this.ReportGenerators[index].Start();
this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, "Faulted Task, and instance of ReportGeneratorThread is recreated and corresponding task is started"));
break;
}
}
}
else if (taskException != null)
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Task " + taskException.Task.Id + " has thrown a Task Canceled Exception"));
}
}
}
}
然后你可以像这样从OnStart()
调用它:
protected override void OnStart(string[] args)
{
// Save the returned Task in a local, just as a hack
// to suppress the compiler warning about not awaiting the call.
// Alternatively, store the Task object somewhere and actually
// do something useful with it.
var _ = this.manager.StartManager();
this.log.LogEvent(this.id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Service started"));
}
请注意,上面建议的更改没有解决我提到的任何奇怪之处。在我看来,该方法的更有用的实现可能看起来像这样:
public async Task StartManager()
{
foreach (var reportGeneratorThread in this.ReportGenerators)
{
reportGeneratorThread.Start();
}
while (true)
{
try
{
Task task = await Task.WhenAny(this.Tasks.ToArray());
if (task.IsFaulted)
{
// Unpack the exception. Alternatively, you could just retrieve the
// AggregateException directly from task.Exception and process it
// exactly as in the original code (i.e. enumerate the
// AggregateException.InnerExceptions collection). Note that in
// that case, you will see only a single exception in the
// InnerExceptions collection. To detect exceptions in additional
// tasks, you would need to await them as well. Fortunately,
// this will happen each time you loop back and call Task.WhenAny()
// again, since all the tasks are in the Tasks collection being
// passed to WhenAny().
await task;
}
}
catch (Exception v)
{
var taskException = v as TaskCanceledException;
if (v != taskException)
{
foreach (var reportGenerator in this.ReportGenerators)
{
if (reportGenerator.Task.IsFaulted)
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Unhandled exception from Task " + reportGenerator.Task.Id));
ReportGeneratorThread faultedReportGeneratorThread = this.GetThreadById(reportGenerator.Task.Id);
var index = this.ReportGenerators.FindIndex(t => t.Equals(faultedReportGeneratorThread));
this.DisposeFaultedThread(faultedReportGeneratorThread, index);
this.ReportGenerators[index].Start();
this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, "Faulted Task, and instance of ReportGeneratorThread is recreated and corresponding task is started"));
break;
}
}
}
else
{
this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Task " + taskException.Task.Id + " has thrown a Task Canceled Exception"));
// Cancelling tasks...time to exit
return;
}
}
}
}
以上将循环,在出现错误的任务时立即重新启动,但如果其中一个被取消,则完全退出。
注意:缺少一个好的代码示例来开始,上面是浏览器代码:完全未编译,未测试。我想不起WhenAll()
和WhenAny()
如何传播异常的具体细节;我想我的例子是正确的,但是完全有可能您需要调整细节以使其工作。