IIS 7.5应用程序池回收不让方法完成
本文关键字:方法 应用 应用程序 程序池 IIS | 更新日期: 2023-09-27 18:13:29
我有两个方法:
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");
?看起来好像是在取消任务,让正在运行的任务完成。(任务在运行前检查是否已取消,否则执行任务)。
From Task.WaitAll
:
AggregationException:
至少有一个Task实例被取消 -或者-在执行至少一个Task实例期间抛出异常。如果任务被取消,AggregateException在其InnerExceptions集合中包含OperationCanceledException。
你正在通过_cancellationTokenSource.Cancel();
取消你的任务,我假设这会导致其中至少一个抛出异常。您可能会在更高级别的堆栈框架中捕获它并忽略它。将Task.WaitAll
封装在try-catch块中:
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
}
}