OT: Static method in ASP.NET question.

OT: Static method in ASP.NET question.

Old forum URL: forums.lhotka.net/forums/t/1623.aspx


tetranz posted on Sunday, October 29, 2006

Hi all

I know how static variables behave in ASP.NET. They lve in AppDomain so are therefore shared among users and can be reset at any time if ASP recycles the process. Here's a question about static methods.

Say I have a collection (or any object) that is unique to a user's session. It hits the db so I cache it in Session. I have something like this in my page class.

public MyCollection GetMyCollection()
{
    MyCollection myCollection = (MyCollection) Session["MyKey"];
    if (myCollection) == null)
    {
        myCollection = MyCollection.GetMyCollection(userId);
        Session["MyKey"] = myCollection;
    }
    return myCollection;
}

I think that's fine because the page is a unique instance but what if I now move it out into a static helper method in another class like this:

public static MyCollection GetMyCollection()
{
    MyCollection myCollection = (MyCollection) HttpContext.Current.Session["MyKey"];
    if (myCollection) == null)
    {
        myCollection = MyCollection.GetMyCollection(userId);
        HttpContext.Current.Session["MyKey"] = myCollection;
    }
    return myCollection;
}

userId is a Guid that comes from my Principal. Is that safe? I'm thinking of what happens if one user loses the processor just before the if statement. What it gets it back again, could myCollection have changed to reflect another user? Am I barking up the wrong tree and worrying about nothing because, I think, myCollection is part of the state that is saved and restored on a context switch.

Cheers
Ross


Copyright (c) Marimer LLC