web api TaskScheduler.UnobservedTaskException

2

I have recently published an asp.net web api to a production web site. On production about once a day the an unhandled exception causes the web site process to recycle:

An unhandled exception occurred and the process was terminated. Application ID: /LM/W3SVC/2/ROOT/oasis Process ID: 9236 Exception: System.AggregateException Message: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. StackTrace: at System.Threading.Tasks.TaskExceptionHolder.Finalize() InnerException: System.Web.HttpException Message: The remote host closed the connection. The error code is 0x800704CD. StackTrace: at System.Web.Http.WebHost.HttpControllerHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

This exception appears to not to originate in program code but in web api internals. I need to prevent such an excetion from recycling the process as this destroys the sessions of numberous users.

I understand that one way to handle this exception is to use :

TaskScheduler.UnobservedTaskException += (sender, e) =>
{
    McpsEventLog.PostException(e.Exception, "webapicontroller");
    e.SetObserved();
};

But for this to work, where can I put this code. somewhere in the web api controller? Or in the global.asax. Does someone know how the UnobserveredTaskException can be impletmented in an asp.net Web Api rest service?

asp.net
.net
asp.net-web-api
task-parallel-library
asked on Stack Overflow Aug 29, 2012 by alecvb • edited Sep 26, 2012 by Adi Lester

1 Answer

4

You are right: Unhandled exception are unacceptable in the context of a web application. The right place to setup that handler is the Application_Start event.

You also should set up UnhandledException-event. It does not allow you to swallow the exception, though. Only log it.

Finally, see my question about this topic: How to treat unhandled thread-exceptions in ASP.NET? I did not get a usable answer but it might still help you.

answered on Stack Overflow Aug 29, 2012 by usr • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0