Should I never call HostingEnvironment.UnregisterO

2019-05-07 18:28发布

问题:

While trying to implement asyncronous email over smtp in my ASP.Net MVC 3 application I've come around SO SmtpClient.SendAsync blocking my ASP.NET MVC Request thread. There I found the article by Phil Haack: The Dangers of Implementing Recurring Background Tasks In ASP.NET which provides a way to avoid crashing of the background thread on AppDomain shutdown.

The article says to call HostingEnvironment.RegisterObject(this); on the constructor and call HostingEnvironment.UnregisterObject(this); only if IRegisteredObject.Stop Method is called.

In a general scenario, when requests arrive permanently, and the scope of the object implementing IRegisteredObject is request, dosn't this approach register objects within each request (utilizing the email functionality) and does not unregister any?

Is it OK? Or should I also unregister after the asynchronous operation completed?

P.S.: as suggested by Damian Edwards in the linked SO question, I use ThreadPool.QueueUserWorkItem to send the email beyond request scope.

回答1:

I'm not sure what you mean by requests arrive permanently, scope of the object ... is request etc.

Request Scope, permanent, and ThreadPool.QueueUserWorkItem; these words together do not make sense at all. One uses ThreadPool.QueueUserWorkItem so that a request does not take forever. The time-consuming job is done in the background while your request returns immediately as Damian Edwards suggests.

I have used IRegisterObject to send bulk e-mails upon a request received. However, in my case, I have used a singleton object EmailSender that implements IRegisterObject. In that case, it is registered once in the constructor and unregistered once in Stop().

So, in short, please use a singleton.