Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exception break application pools?

I have the web api app with this method

public class TestController
{
     public UserView Get()
     {
            var testThread = new Thread(() => { throw new Exception(); });
            testThread.Start();
            Thread.Join();
            Thread.Sleep(1000);
            return null;
     }
}

When i request this method, my application pools breaks. I receive this window enter image description here

And broken an application pools. enter image description here When i have this method

        var task = new Task(() => { throw new Exception(); });
        task.Start();

everything is good. Why?

like image 229
kriper Avatar asked Jul 12 '26 15:07

kriper


2 Answers

I guess because Task does not throw exceptions it return it as a property of Task object. If you does not check Task result it even won't be thrown until application start shutdown sequence and then it will be thrown as UnhandledException. I guess in Thread is different

like image 70
Alex F Avatar answered Jul 15 '26 04:07

Alex F


That's just how ASP.NET works. If a thread has an unhandled exception that isn't tied to a request, then it will bring the application down. This is described on Phil Haack's blog. He mentioned a detail followup post explaining specifically why comes down, but I was unable to find the followup post.

Depending on what you need to do in another thread, you can use an alternative such as async code, QueueBackgroundWorkItem, or a scheduler that has been specifically designed to work around these limitations such as Hangfire, WebBackgrounder or Quartz.NET.

like image 28
mason Avatar answered Jul 15 '26 05:07

mason