HttpContext.Current.Items in different thread

2020-04-17 04:15发布

问题:

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** ?
    }


}

回答1:

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



标签: asp.net