任务OutOfMemory异常不会终止进程

时间:2013-12-30 14:15:09

标签: c# exception-handling task-parallel-library

我有一个成功的以及有故障的延续的任务代码。

Task<IEnumerable<IDictionaryObject>> getParameters = _parametersRequester.BeginGetParametersBulk(requestJob);

var processParameters = 
getParameters.ContinueWith((x) =>
    {
         //Do some processing
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

getParameters.ContinueWith((x) =>
    { 
        AggregateException ex = x.Exception;
        ex.Flatten().Handle(ie => HandleException(requestJob, canRetry, ie));
    }, TaskContinuationOptions.OnlyOnFaulted);

return processParameters;

如果发生异常,则HandleException重试某些操作,如果遇到未知异常则返回false。 我看到的问题是 getParameters 抛出OutOfMemoryException,它应该在GC终结器运行时终止进程,但它们似乎没有运行,因此进程仍然在运行且处于不稳定状态。

如果HandleException返回false,有没有办法强制进程终止?

1 个答案:

答案 0 :(得分:4)

Handle未处理的例外情况会重新打包到新的AggregateException并重新投放。

在.NET 4.5中,默认行为是未观察到的任务异常不会取消该过程。

要更改此设置(并恢复.NET 4.0行为),请将以下内容添加到您的应用配置中:

<configuration> 
    <runtime> 
        <ThrowUnobservedTaskExceptions enabled="true"/> 
    </runtime> 
</configuration>

有关详细信息,请参阅here

您最好观察异常,如果不能正常关闭,至少应用您的应用程序日志记录报告异常或类似:

System.Environment.Failfast("Meaningful error message.", exception);
相关问题