异步 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 "我猜你快中奖了";
}
}

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3