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 "我猜你快中奖了";
       }
    }
  • 相关阅读:
    python基础(9):基本数据类型四(set集合)、基础数据类型补充、深浅拷贝
    python基础(8):基本数据类型三(dict)、is和==、编码和解码
    python基础(7):基本数据类型二(list、tuple)、range
    python基础(1):python介绍、python发展史
    python基础(6):基本数据类型一(int、bool、str)
    python基础(5):格式化输出、基本运算符、编码问题
    python基础(4):用户交互、if判断、while循环、break和continue
    python基础(2):python的安装、第一个python程序
    python基础(3):变量、常量、注释、基本数据类型
    java基础(32):类加载、反射
  • 原文地址:https://www.cnblogs.com/whtydn/p/1524580.html
Copyright © 2011-2022 走看看