Solved

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

Posted on 2009-05-13
6
426 Views
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;

        d.Start();
 

        

        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());

            }

            else

            {

                context.Cache["xxx"] = "Current Loop Value:=" + i.ToString();

            }

            

            

            

            Thread.Sleep(3000);

        }
 

       
 
 

        context.Cache["xxx"] = "Done";

    }

Open in new window

0
Comment
Question by:ziorrinfotech
  • 4
  • 2
6 Comments
 
LVL 39

Expert Comment

by:abel
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.
0
 

Author Comment

by:ziorrinfotech
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.
0
 
LVL 39

Expert Comment

by:abel
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 --
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 39

Expert Comment

by:abel
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?
0
 

Author Comment

by:ziorrinfotech
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?
0
 
LVL 39

Accepted Solution

by:
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 --
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

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…
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
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…

707 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now