我有两种方法:
public void Stop(bool immediate)
{
Logger.Log(LogLevel.Debug, "Shutdown detected. Immediate: " + immediate);
Shutdown();
Logger.Log(LogLevel.Debug, "Unregistering");
HostingEnvironment.UnregisterObject(this);
}
public void Shutdown()
{
Logger.Log(LogLevel.Debug, "Preparing to stop UploadQueue");
IsProcessing = false;
//Set tasks to cancel to prevent queued tasks from parsing
_cancellationTokenSource.Cancel();
Logger.Log(LogLevel.Debug, "Waiting for " + _workerTasks.Count + " tasks to finish or cancel.");
//Wait for tasks to finish
Task.WaitAll(_workerTasks.Values.ToArray());
Logger.Log(LogLevel.Debug, "Stopped UploadQueue");
}
该类正在使用IRegisteredObject接口来接收关闭通知。在我的日志中,我得到了这个:
2014-07-18 15:30:55,913,DEBUG,Shutdown detected. Immediate: False
2014-07-18 15:30:55,913,DEBUG,Preparing to stop UploadQueue
2014-07-18 15:30:55,913,DEBUG,Waiting for 35 tasks to finish or cancel.
...
bunch of stuff
...
2014-07-18 15:31:28,471,DEBUG,Shutdown detected. Immediate: True
2014-07-18 15:31:28,471,DEBUG,Preparing to stop UploadQueue
2014-07-18 15:31:28,471,DEBUG,Waiting for 0 tasks to finish or cancel.
2014-07-18 15:31:28,471,DEBUG,Stopped UploadQueue
2014-07-18 15:31:28,471,DEBUG,Unregistering
为什么第一次没有进入Logger.Log(LogLevel.Debug, "Stopped UploadQueue");
?它肯定似乎取消了任务并让正在运行的任务完成。 (任务检查在运行之前是否取消了,否则就行了)。
答案 0 :(得分:1)
来自Task.WaitAll
:
<强> AggregationException:强>
至少有一个任务实例被取消 - 或者 - 在执行至少一个Task实例期间抛出了异常。如果任务被取消,则AggregateException在其InnerExceptions集合中包含OperationCanceledException。
您正在通过_cancellationTokenSource.Cancel();
取消您的任务,我认为这导致其中至少有一人抛出异常。您可能会在更高级别的堆栈框架中捕获它并忽略它。在try-catch块中包装Task.WaitAll
:
public void Shutdown()
{
Logger.Log(LogLevel.Debug, "Preparing to stop UploadQueue");
IsProcessing = false;
//Set tasks to cancel to prevent queued tasks from parsing
_cancellationTokenSource.Cancel();
Logger.Log(LogLevel.Debug, "Waiting for " + _workerTasks.Count + " tasks to finish or cancel.");
try
{
//Wait for tasks to finish
Task.WaitAll(_workerTasks.Values.ToArray());
Logger.Log(LogLevel.Debug, "Stopped UploadQueue");
}
catch (AggregationException e)
{
// Recover from the exception
}
}