Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 649
usr Avatar asked Jun 20 '12 10:06

usr


1 Answers

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

like image 82
Jupaol Avatar answered Oct 26 '22 23:10

Jupaol