httpcontext object gives error when it is access in a different thread

Posted on 2009-05-13
Last Modified: 2012-05-06
I have a web form which has a button and when user clicks on the button then i am calling a aspx form (default2.aspx) using jquery.ajax method.

default2 create object of class1 and call dowork funtion in a different thread

now what is happening is i am trying to access htttpcontext in dowork function
but it gives me error on this  if (context.Cache["xxx"] == null)
it says object reference is not set.
and when i debug this i found out that context becomes null as soon as the ajax calls gets complete.

why it is happening, cannot i access server side cache in a different thread.
here is default2.aspx code
protected void Page_Load(object sender, EventArgs e)
        Class1 cls = new Class1();       
        ThreadStart s = new ThreadStart(cls.dowork);
        Thread d = new Thread(s);
        d.IsBackground = true;
        Response.Write("work doe");
here is dowork code
  public virtual void dowork()  {
        HttpContext context = HttpContext.Current;
        for (int i = 0; i < 5; i++) 
            if (context.Cache["xxx"] == null)
                context.Cache.Insert("xxx", "Current Loop Value:=" + i.ToString());
                context.Cache["xxx"] = "Current Loop Value:=" + i.ToString();
        context.Cache["xxx"] = "Done";

Open in new window

Question by:ziorrinfotech
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
LVL 39

Expert Comment

ID: 24376767
> why it is happening, cannot i access server side cache in a different thread.

that is quite correct. The HttpContext object is created only during the lifecycle of a request. You can access it, but it will only be set during a request and destroyed at the end of it. More precisely,it is part of HttpApplication class, which is created at the beginning of the request and destroyed at the end. With its destruction, its members, like Context, are destroyed also.

If you need information from the Context you should add that to your Worker class using different techniques. You cannot rely on it to keep a reference to the Context object. Trying to keep it alive (if at all possible) will probably yield unpredictable results with other requests.

Author Comment

ID: 24376800
hi abel

is there any different way of storing a string which is globally accessible so that when i come back again even on a different page then i can access that string.
LVL 39

Expert Comment

ID: 24376890
From your code above it seems that all you want to do is add some items to the Cache of the HttpContext. You may be aware of the fact that the HttpContext.Cache is basically the AppDomain's cache object, that you can retrieve by calling HttpRuntime.Cache. In turn, the HttpRuntime will callt he RuntimeConfig.GetAppConfig().Cache method to retrieve the cache (but it does a bit more too, so don't do this at home).

Because the HttpRuntime.Cache is a static property, it is a thread-safe operation to retrieve it.

-- Abel --
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

LVL 39

Expert Comment

ID: 24376926
> that when i come back again even on a different page then i can access that string.

aha, that is about something totally different. Normally, you use Sessions for that. But you do not need a worker process in a separate thread for adding strings to a Session, do you? More globally is also possible (using Application[key] = value), but it is often preferred to use a database instead.

May I ask: why do you want to use a different thread? Is there a necessity for using a new thread or were you merely experimenting?

Author Comment

ID: 24377429
here is my whole requirement.

I am working on a website which downloads around 20 to 30 xml files from ftp location and insert them into database.

and i want to show some sort of progress to the end user instead of just showing a gif image when this process is going.
this dowork function will in actual do all the above things. and I will write one more function will be called after regular interval to read the update string from the cache so that this string can be shown on the user browser.

so if I use Session or Application here would that be a better choice for me instead of cache?
and if yes then how can i access the session and application object inside a class code?
LVL 39

Accepted Solution

abel earned 250 total points
ID: 24378970
You actually need a different approach, it seems. But rethinking your story, it seems that the working thread is not working too long. You can give it a pointer to the Session, which will be alive until the session times out, which is, since the last request, by default 30 minutes.

The good thing is, that the Session is automatically bound to the user/browser/client that made the request. So it won't become a problem if you would have multiple users simultaneously calling that method. Using Applciation or the Cache objects, you would have to add a lot of logic to prevent collision with other requests, since they all share the same memory space.

So, in short: use Sessions, that is your way to go.

-- Abel --

Featured Post

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

624 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question