Search code examples
c#asp.netmultithreadingthread-safetyhttpcontext

HttpContext Class and its Thread Safety


I have an Singleton object in application that has following property:

private AllocationActionsCollection AllocationActions
{
    get
    {
        return HttpContext.Current.Session["AllocationOptions.AllocationActions"] as AllocationActionsCollection;
    }
    set
    {
        HttpContext.Current.Session["AllocationOptions.AllocationActions"] = value;
    }
}

I'm dealing with one error (HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null even though it is supposed to me always set to valid instance...). I just read in MSDN that HttpContext instance member are not guaranteed to be thread safe! I wonder if that could be the issue. There could be a resources race somewhere in application and the moment where HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null is the moment where AllocationActions setter is used using this statement:

AllocationActions = new AllocationActionsCollection(Instance.CacheId);

My questions are:

a) I'm shocked that HttpContext.Current.Session is not thread safe. How to safely use that property then? b) do you have any ideas why that Session variable can be null (even though I'm pretty sure I'm setting it before it's used for the first time)?

Thanks,Pawel

EDIT 1:

a) line that initializes session variable is set every 2 minutes with following statement (executed in Page_Load)

AllocationActions = new AllocationActionsCollection(Instance.CacheId);

b) code that calls getter is called in event handlers (like Button_Click)

c) there is not custom threading in application. only common HTTP Handler


Solution

  • A singleton object is realized by restricting the instantiation of a class to one object.

    HttpContext.Current.Session is an area dedicated to a single user; any object stored in Session will be available only for the user/session that created it.

    Any object stored in Application will be available only for every user/session.

    Any static object also, will be available only for every user/session. Suggested implementations always use static objects.. why didn't you?