What is the preferred approach to initialize one-time logic in ASP.NET 3.5 WebForms?
-
20-06-2021 - |
题
Scenario:
- I have a ASP.NET 3.5 WebForms based website.
- It contains
Foo.aspx
,Bar.aspx
andbaz.html
(jQuery template). - Typical traffic seen is
Foo.aspx
(N times),Bar.aspx
(N times) andbaz.html
(10*N times). - ASP.NET worker process (
aspnet_wp.exe
) is recycled say every 2 hours. - There exists an older API (
OldFooService.Init()
) which needs to be executed only for the first request ofFoo.aspx
.OldFooService.Init()
initializes a data-store intoCache
for the very first flow, but fires blanks for subsequent flows.
Question:
I am currently doing B (see below) since the traffic to Foo.aspx
is lower than baz.html
and OldFooService.Init()
fires blanks after the first time.
Should I use C? Writing to Application_State
requires locking (MSDN) and its not guaranteed to be available, so not sure if its worth the effort. Or is there a much better D?
Options:
A) In Application_Start
of Global.asax
B) In Page_Load
of Foo.aspx
once (by checking Not IsPostBack
)
C) Option B + use a flag in ApplicationState
to run once per recycle of aspnet_wp.exe
.
解决方案
The correct answer here is (A), use Global.asax. B won't work as subsequent GET requests will run the same code. C will work, but is ugly as sin.
I would recommend handling Application_Start or Application_Init in Global.asax, depending on what's required in your legacy init function.
其他提示
If it's ok for OldFooService.Init() to be called a few extra times in the event of requests coming in simultaneously before its initialized then I would go with C. If it absolutely must run once per recycle, then I would use a static class with some proper read/write locks.
On a side note, is the worker process actually recycled every 2 hours? That seems rather frequent.