多線程或者異步調用中如何訪問HttpContext?
前面我還提到在APM模式下的異步完成回調時,訪問HttpContext.Current也會返回null,那么此時該怎么辦呢?
答案有二種:
1. 在類型中添加一個字段來保存HttpContext的引用(異步開始前)。
2. 將HttpContext賦值給BeginXXX方法的最后一個參數(object state)
建議優先選擇第二種方法,因為可以防止以后他人維護時數據成員被意外使用。
引用:
不錯的文章:http://www.cnblogs.com/fish-li/archive/2013/04/06/3002940.html#_label5
http://bbs.csdn.net/topics/300139110
http://www.tuicool.com/articles/vYVziy
本文章轉載:http://www.codesky.net/article/201004/103725.html
異步 HttpContext.Current實現取值的方法(解決異步Application,Session,Cache...等失效的問題)
回答的也多數都是:引用System.Web,不要用HttpContext.Current.Application應該用System.Web.HttpContext.Current.Application,后來在網上看到一篇關於System.Runtime.Remoting.Messaging.CallContext這個類的詳細介紹才知道,原來HttpContext.Current是基於System.Runtime.Remoting.Messaging.CallContext這個類,子線程和異步線程都無法訪問到主線程在CallContext中保存的數據。所以在異步執行的過程會就會出現HttpContext.Current為null的情況,為了解決子線程能夠得到主線程的HttpContext.Current數據,需要在異步前面就把HttpContext.Current用HttpContext的方式存起來,然后能過參數的形式傳遞進去,下面看看實現的方法:
public HttpContext context
{
get { return HttpContext.Current; }
set { value = context; }
}
然后建立一個委托
public delegate string delegategetResult(HttpContext context);
下面就是實現過程的編碼
protected void Page_Load(object sender, EventArgs e)
{
context = HttpContext.Current;
delegategetResult dgt = testAsync;
IAsyncResult iar = dgt.BeginInvoke(context, null, null);
string result = dgt.EndInvoke(iar);
Response.Write(result);
}
public static string testAsync(HttpContext context)
{
if (context.Application["boolTTS"] == null)
{
Hashtable ht = (Hashtable)context.Application["TTS"];
if (ht == null)
{
ht = new Hashtable();
}
if (ht["A"] == null)
{
ht.Add("A", "A");
}
if (ht["B"] == null)
{
ht.Add("B", "B");
}
context.Application["TTS"] = ht;
}
Hashtable hts = new Hashtable();
hts = (Hashtable)context.Application["TTS"];
if (hts["A"] != null)
{
return "恭喜,中大獎呀";
}
else
{
return "我猜你快中獎了";
}
}
