【问题标题】:HttpContext.Current.Items in different thread不同线程中的 HttpContext.Current.Items
【发布时间】:2013-03-04 07:26:17
【问题描述】:

使用 HttpContext.Current.Items 我们可以访问当前请求中的变量

我的问题是,如果请求移动到不同的线程,我们还能访问它吗?

如果是,我们如何访问它?

我假设它会抛出空引用异常?

我正在尝试使用下面的代码,但它会引发 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** ?
    }


}

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    无论 ASP.Net 决定在哪个线程上运行请求,您都可以始终从当前请求访问 HttpContext.Current.Items

    如果您特别询问异步操作的行为,ASP.Net 运行时将为您透明地处理所有线程问题。有关该主题的更多信息,我建议

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

    【讨论】:

    • 因此,如果我在页面加载时具有三个功能。我可以创建三个线程并调用线程启动吗?后者加入线程?
    • @Shekhar:我不建议你这样做。如果您需要获取外部资源,请使用 .NET 4.5 中可用的异步编程模型(如果您使用的是 MVC 4,请参阅我的答案中的链接)。如果您确实启动了一堆线程然后加入它们,您将能够从其他线程访问HttpContext.Current。请记住,HttpContext.Current 本质上不是线程安全的。见stackoverflow.com/questions/734821/…
    • 我已经更新了我正在尝试做的代码,关于如何使它工作的任何建议
    • 将 HttpContext.Current.Items 传递给Threadclas 的构造函数,或者作为参数传递给Datamethod。确保在加入生成的线程之前不要退出BtnClick。您的班级Threadclas 无权访问HttpContext.Current.Items,因为它是WebForm1 的静态属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多