Friday, March 16, 2012

Member Variables in ASP.Net Pages

I've been having a debate with some former Java servlet programmers. They contend that code-behind classes (derived from the Page class) are very similar to servlets in that you need to be careful about threading issues. That is, private and protected member variables defined in the Page-derived code-behind class are not thread-safe and must be protected by synchronization (or, better still, not used at all).
I disagree because ASP.Net creates new instances of the Page-derived code-behind object with each request, postback or not. Much of the info that I've read on this subject kind of skirts the issue by saying that the Page-derived object is "released" - implying that it is sent back to some pool of page objects which can be used again by another request.
So, is there anyone out there who can settle this? Is it safe to use member variables within your Page-derived class? Or, are you flirting with disaster if different users hit your page code at almost the same time and step on one another's member variable value?
(I apologize for re-posting this, but I originally posted in the Web Forms section and the question got buried and never was answered. I was hoping for better luck in this section.)
Hi,
yes it is safe.
Detailed explanation is here:http://msdn.microsoft.com/msdnmag/issues/03/06/Threading/default.aspx
Shortly:
- every request gets distinct class instance
- Page class (HTTP Handler) instances are not pooled by default (only custom handlers could be), it is controlled by IHttpHandler.IsReusable property
- I suppose that the latter is confused with Framework's thread pooling which happens with ASP.NET request processing

0 comments:

Post a Comment