非同步 HttpContext.Current實現取值的方法(解決非同步Application,Session,Cache…等失效的問題)

來源:互聯網
上載者:User

回答的也多數都是:引用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 "我猜你快中獎了";
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.