随笔 - 163  文章 - 2  评论 - 370  阅读 - 46万 

在一个项目中,为了系统执行效率更快,把一个经常用到的数据库表通过dataset放到Application中,发现在异步实现中每一次都会出现HttpContext.Current为null的异常,后来在网上查了好多资料,发现问这个问题的人多,回答的少,回答的也多数都是:引用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 { context = value ; }
}
然后建立一个委托
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, nullnull);
   
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 "我猜你快中奖了";
   }
}
复制代码

 

posted on   风浪  阅读(6081)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示