How to treat unhandled thread-exceptions in ASP.NET?

坚强是说给别人听的谎言 提交于 2020-01-01 05:06:44

问题


How is an ASP.NET application supposed to deal with unhandled exceptions which are occuring on a non-request background thread (due to bugs)?

By default, such exceptions cause the process to terminate. This is unacceptable in the setting of an ASP.NET worker process because concurrently running requests are aborted unpredictably. It is also a performance problem.

Exceptions on a request thread are not a problem because ASP.NET handles them (by showing an error page).

The AppDomain.UnhandledException event allows to observe that an exception has occurred, but termination cannot be prevented at that point.

Here is a repro which needs to be pasted into an ASPX page codebehind.

protected void Page_Load(object sender, EventArgs e)
{
    var thread = new Thread(() =>
        {
            throw new InvalidOperationException("some failure on a helper thread");
        });
    thread.Start();
    thread.Join();
}

The only solution I know of is to never let an exception "escape" unhandled. Is there any other, more global and thorough solution for this?


回答1:


Rx (Reactive Programming) was born to solve issues like this, try to consider changing the framework you currently use and replace it with Rx

http://msdn.microsoft.com/en-us/data/gg577609.aspx

The Nugget packages:

https://nuget.org/packages/Rx-Main/1.0.11226

This is the equivalent Rx code:

        var o = Observable.Start(() => { throw new NotImplementedException(); });

        o.Subscribe(
            onNext => { },
            onError => { },
            () => { Console.WriteLine("Operation done"); });

As you can see the error won't escape the background thread when you specify a handler for the error, onError => { }

If you do not specify an error handler, the exception will be propagated:

        o.Subscribe(
            onNext => { },
            () => { Console.WriteLine("Operation done"); });

In the example above, the exception will be propagated and will cause the same problems as your posted code




回答2:


You can mark the exception as handled in an unhandled exception handler. https://msdn.microsoft.com/en-us/library/system.windows.applicationunhandledexceptioneventargs.handled(v=vs.95)

That should prevent the worker process from recycling because of an error on the background thread.

You wouldn't do that for all exceptions though. Just the ones you know are safe to ignore.




回答3:


I think "legacyUnhandledExceptionPolicy" option is your answer.

Unhandled exceptions causing ASP.NET to crash in .NET 2.0 ; http://blogs.msdn.com/b/tom/archive/2007/12/04/unhandled-exceptions-causing-asp-net-to-crash-in-net-2-0.aspx



来源:https://stackoverflow.com/questions/11117167/how-to-treat-unhandled-thread-exceptions-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!