当前位置: 移动技术网 > IT编程>开发语言>.net > 异步 HttpContext.Current实现取值的方法(解决异步Application,Session,Cache...等失效的问题)

异步 HttpContext.Current实现取值的方法(解决异步Application,Session,Cache...等失效的问题)

2017年12月12日  | 移动技术网IT编程  | 我要评论

金棕榈大奖,暗恋一个人的表现,泰安鱼缸

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网