zoukankan      html  css  js  c++  java
  • 异步 HttpContext.Current实现取值的方法(解决异步Application,Session,Cache...等失效的问题)

    在一个项目中,为了系统执行效率更快,把一个经常用到的数据库表通过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 "我猜你快中奖了";
       }
    }
  • 相关阅读:
    [BZOJ 4318] OSU!
    [BZOJ 4720][NOIP 2016] 换教室
    [Tyvj 1729] 文艺平衡树
    [BZOJ 1500]维修数列 [Splay Tree从进阶到住院]
    [学习笔记] CDQ分治 从感性理解到彻底晕菜
    [COGS 1752] 摩基亚Mokia
    [Tyvj 1730] 二逼平衡树
    [学习笔记] Splay Tree 从入门到放弃
    [Tyvj 1728] 普通平衡树
    [BZOJ 3594] 方伯伯的玉米田
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3565178.html
Copyright © 2011-2022 走看看