views:

619

answers:

2

The background to this question is that I need to use some user session data in a (static) WebMethod. I have created a static property that references the data I need like so:

private static UserWebSession UserWebSession
{
    get
    {
        return (UserWebSession)HttpContext.Current.Session["UserWebSession"];
    }
}

I can then call this in my page's static WebMethod.

My question is, is this technique thread safe? Or will this property's value be updated with every new page request - in other words, it will return the UserWebSession for the user who most recently requested the page?

+3  A: 

That's fine - HttpContext.Current is designed precisely for this sort of thing. You won't get a previous user's session.

It's dependent on the thread though (I believe) - so if you start any extra background threads, they won't be able to see the current context.

Also be aware that although this call is safe in terms of not getting the wrong context, the normal concurrency caveats apply when it comes to what you actually do with the context.

Jon Skeet
brilliant, thanks john. caveats understood.
MalcomTucker
A: 

I don't know that a Page Method is able to access Session state. If it can, then you may be ok. I recall that access to Session state is serialized, so that only one request at a time can arrive for a given session.

John Saunders