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 --
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

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

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer…
PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
The viewer will learn how to dynamically set the form action using jQuery.
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…

734 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