开发者

static class in Asp.NET MVC app

I am wondering if a static class in an ASP.开发者_StackOverflowNET MVC app could be initialized more than once. I initially designed my app so that a static component would fetch some stuff from the database and serve as a cache, and I added a refresh method to the class which was called from the constructor. The refresh method was also made available through the administration portion of the app. At some point I noticed that the data was updated without requiring this manual trigger, which implies that the static constructor run more than once.

There are several scenarios where I could reasonably see this happen, such as an unhandled Exception causing re-initialization. But I am having trouble reproducing this, so I would like to know for sure.


The most usual scenarios would be:

  • a reload of the web application

    • touched Web.config
    • touched binaries
    • abnormal termination (out-of-memory, permission errors)
  • a reload of the Application Pool

  • a restart of IIS
  • a restart of w3wp.exe (at least once in 29 hours!)

The app-domain will get reloaded (recompiling the dynamic parts as necessary) and this would void any statically initialized data.

You can get around that by persisting the static data somewhere if creating it is expensive, or avoid reloading the AppDomain, the Application Pool or the IIS server.

Update: Phil Haack just published a relevant blog entry here: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

  • Bye Bye App Domain
    • it does a better job at explaining the above. Notable, IIS will recycle it's worker process very 29 hours at minimum and shared hosters will recycle AppDomain much more often (perhaps in 20 minutes of idle time)
  • So tell ASP.NET, “Hey, I’m working here!”
    • outlines techniques you can apply to get notified of an AppDomain take down - you could use this to get your Singleton instance behaving 'correctly'
  • Recommendation

I suggest you read it :)


static classes are initialized once per AppDomain.

If IIS recycles your AppDomain, everything will re-initialize.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜