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

Posted on 2009-05-13
Medium Priority
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 --
Create CentOS 7 Newton Packstack Running Keystone

A bug was filed against RDO for the installation of Keystone v3. This guide is designed to walk you through the configuration for using Keystone v3 with Packstack. You will accomplish this using various repos and the Answers file.

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 750 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

PowerShell Core for Advanced Linux Administrators

Understand advanced principals around Powershell Core with a focus on the Linux Administrator.  This course covers how to administer numerous environments across multiple platforms including Linux, Azure, AWS, and Google Cloud from a single shell instance.

Question has a verified solution.

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

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
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…
Suggested Courses

719 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