2

Using HttpContext.Current.Items we can access variables from current request

My question is what if the request moves to different thread, can we still access this ?

if Yes, how can we access it ?

I assume it will throw null reference exception ?

I am trying with the below code, but it throws Null Ref Exception

    public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void BtnClick(object sender, EventArgs e)
    {
        HttpContext.Current.Items["txtbox1"] = txtbox1.Value;
        var t = new Thread(new Threadclas().Datamethod());
        t.Start();
                }
}

public class Threadclas
{
    public void Datamethod()
    {
        var dat = HttpContext.Current.Items["txtbox1"];
        **//how can i access HttpContext here** ?
    }


}
user804401
  • 1,990
  • 9
  • 38
  • 71

1 Answers1

3

You can always access HttpContext.Current.Itemsfrom the current request, no matter which thread ASP.Net decides to run the request on.

If you're specifically asking about behavior with async actions, the ASP.Net runtime will handle all threading issues transparently for you. For more information on that topic, I suggest

http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • So if I have three function on page load. Can I Create three thread and call thread-start. And latter join the thread? – शेखर Mar 04 '13 at 07:30
  • @Shekhar: I would not suggest that you do that. If you need to fetch external resources, use the async programming model available in .NET 4.5 (and see the link in my answer if you're using MVC 4). If you really do spin up a bunch of threads and then join on them, you will be able to access `HttpContext.Current` from the other threads. Keep in mind though that `HttpContext.Current` is not inherently thread-safe. See http://stackoverflow.com/questions/734821/using-an-httpcontext-across-threads – Eric J. Mar 04 '13 at 07:35
  • I have updated my code that i am trying to do, any suggestions on how to make it work – user804401 Mar 04 '13 at 13:21
  • Pass in HttpContext.Current.Items to the constructor of `Threadclas`, or as a parameter to `Datamethod`. Make sure that you don't exit `BtnClick` until you have joined with the thread(s) that you spawn off. Your class `Threadclas` has no access to `HttpContext.Current.Items` because it is a static property of `WebForm1`. – Eric J. Mar 04 '13 at 17:44