How to store objects in application state?

M

Mel

This may be a stupid question, but here goes...

I have created a NameValueCollection in my website's application state. If,
during a page request, I add a string key and string value to the
collection, how are they stored? Strings are objects so I'm really only
passing references, right? Now I assume that request handlers run in
different threads with their own memory spaces, and when the request ends,
the memory space is unaloted, taking with it my string objects. What am I
missing here?
 
G

Guest

Hi Mel,

A point you are missing can be the fact that the application state bag is
not deallocated when the request ends. The application state bag (referenced
by this.Application) is active as long as the application runs and it's an
application wide storage area.

When you pass a string to the application object, the reference of the
string object is passed so you are right on that. When the application
shutdowns, then this reference is gone and at this moment, the string is now
garbage. Since string is a managed type, it's garbage collected
automatically. Coming back to the namevalue collection, your application
state bag keeps a reference to the namevalue collection on the memory. All
other objects kept inside the namevalue collection are referenced through
this reference. Namevalue collection simply keeps reference to objects that
you store in it. So once this reference to the namevalue is gone, so are the
references to other objects.

In general, there are levels of storage options in ASP.NET. You can store
variables on the page level, on the session level and on the application
level. All of them work similiarly as described above, with the exception of
when they are destroyed.

When you create the string on the page, you get a reference and this
reference is destroyed when the page object is deallocated. But, since you
add the string also to the namevalue collection, which is active in the
Application state bag, another reference is still pointing at it. So it's not
lost, hence it's not deallocated.

Ethem Azun
 
M

Mel

Thanks Ethem,

so basically object lifetime issues are the same across threads as they are
within a thread. The main thing I have to deal with is concurrent access to
shared objects. To do this I use such things as C#'s lock() mechanism, and
the synchronised wrappers available for some intrinsic classes such as
Hashtables.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top