欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-08-13 07:35:51|栏目:.NET代码|点击:
回答的也多数都是:引用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 "我猜你快中奖了";
}
}

上一篇:IE 性能分析工具(asp.net环境)

栏    目:.NET代码

下一篇:C#实现较为实用的SQLhelper

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

本文地址:http://www.codeinn.net/misctech/166471.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有