2013-03-04 73 views
2

使用HttpContext.Current.Items我們可以從當前請求訪問的變量HttpContext.Current.Items在不同的線程

我的問題是,如果請求移動到不同的線程,我們仍然可以訪問這個是什麼?

如果是,我們如何訪問它?

我認爲它會拋出空引用異常?

我想用下面的代碼,但它拋出空參考異常

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


} 

回答

3

您可以隨時訪問HttpContext.Current.Items當前請求,無論哪個線程ASP.Net決定上運行要求。

如果您具體詢問有關異步操作的行爲,則ASP.Net運行庫將爲您透明地處理所有線程問題。有關該主題的更多信息,我建議

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

+0

所以,如果我有在頁面加載三個功能。我可以創建三個線程並調用線程啓動。後者加入線程? – 2013-03-04 07:30:37

+0

@Shekhar:我不會建議你這樣做。如果您需要獲取外部資源,請使用.NET 4.5中提供的異步編程模型(如果您使用的是MVC 4,請參閱我的答案中的鏈接)。如果你真的搞了一堆線程,然後加入它們,你將能夠從其他線程訪問'HttpContext.Current'。請記住,雖然'HttpContext.Current'本質上不是線程安全的。請參閱http://stackoverflow.com/questions/734821/using-an-httpcontext-across-threads – 2013-03-04 07:35:29

+0

我已更新我的代碼,我正在嘗試做的任何建議如何使其工作 – user804401 2013-03-04 13:21:20