开发者

Is a static object/variable stored on cache/session in a web application on .NET?

I'm having some trouble recently.

On a WebForm I declare a static object, like this :

public static MyObject myobject=new MyObject();
Response.Write(myobject.Title());

now, if I load another page that doesn't contain the declaration of myobject and I do again

Response.Write(myobject.Title());

I see the previosly result. Is the object stored on session during the navig开发者_Go百科ation due to the static? And it's reckon by the VIEWSTATE? Or what's happening?


No it's stored as a static variable in the process, which can be recycled at any point, assuming you use IIS.

In short, try not to use static variables in this situation.

To expand on what is happening. The static variable is stored in the server's process, which is controlled by IIS. It just so happens that the process is still alive when you call back onto the server. IIS can recycle this process at any time.

Update: OK more accurately it is per AppDomain, which sits in a process - substitute the word process with AppDomain in my previous paragraphs :-)


It's just a static variable. It "lives" alongside the type - so it will be shared by all code accessing the same field via the same type in the same AppDomain. It will be lost on AppDomain recycle, and won't be shared across multiple servers, etc.

Basically it's not a good idea to use static variables in webapps other than occasionally for local caching...


Static objects are shared across users. It is not stored in session which is unique to user or view state which is unique to each page.

Read up on ASP .NET State Management Recommendations to find out which type of state management feature to use for which scenario.


If it helps, I tend to take the view that you can declare two separate objects within one class - the dynamic object definition and the static object. Normally, if you are creating these within the same class definition, there is a connection between them, and they work in tandem ( the singleton patten is a prime example ).

What it means is that the object is created based on the dynamic object. There is still a static object unaffected by the creation of the dynamic object(s). Because this can be confusing, you should not combine the two without being careful and understanding the distinction between them.

I realise that this is not a real understanding of what is happening, but it helps me to keep in my head the distinction. Each type has its own use, and should be used appropriately ( I have seen dynamic classes that should have been static, as well as the other way round ).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜