多线程下HttpContext.Current 的问题

在项目中需要记录文本日志,为了加快响应速度所以用到了多线程。

但是以前的方法是不支持多线程的,程序运行错误。

追踪代码发现提示HttpContext为空。

1.HttpContext.Current表示当前HttpRequest   对应的Context对象

httpContext.current在不同的httpRequest   中是变化的  
       也就是说用httpConext.current.items来保存的数据是不能跨页面传递的。

2.HttpContext.Current只能从当前正在执行的线程中返回值

3.HttpContext.Current   
     这个会跟Thread.CurrentContext相关,多线程切换的时候   
     HttpContext.Current会被替换为当前线程的Context的。

一般会用到System.Web.HttpContext.Current.Server.MapPath方法,这时就不能用了所以可以用

System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);代替

还有一个就是文件操作不要用静态方法,会造成文件占用等问题。

 

多线程获取不到HttpContext

 

问题一:多线程下获取文件绝对路径

  当我们使用HttpContext.Current.Server.MapPath(strPath)获取绝对路径时HttpContext.Current为null,解决办法如下: 

   ///   
        /// 获得当前绝对路径  
        ///   
        /// 指定的路径  
        /// 绝对路径  
        public static string GetMapPath(string strPath)  
        {  
            if (strPath.ToLower().StartsWith("http://"))  
            {  
                return strPath;  
            }  
            if (HttpContext.Current != null)  
            {  
                return HttpContext.Current.Server.MapPath(strPath);  
            }  
            else //非web程序引用  
            {  
                strPath = strPath.Replace("/", "\\");  
                if (strPath.StartsWith("\\") || strPath.StartsWith("~"))  
                {  
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');  
                }  
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);  
            }  
        }  

 

问题二:多线程下获取缓存问题

 多线程下使用HttpContext.Current.Cache.Get(key)获取缓存时HttpContext.Current为null,解决办法如下:

HttpRuntime.Cache.Get(key);

从MSDN上的解释可以看出,HttpRuntime.Cache是应用程序级别的,而HttpContext.Current.Cache是针对当前WEB上下文定义的。

然而,实际上,这二个都是调用的同一个对象,不同的是:HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。

而HttpContext则只能用在WEB中。因此,在可能的情况下,我们尽可能使用HttpRuntime(然而,在不同应用程序之间如何调用也是一个问题)。

问题三:多线程下使用Html转码问题

多线程下使用HttpContext.Current.Server.HtmlEncode(Htmlstring)转码HttpContext.Current为null,解决办法如下:

HttpUtility.HtmlEncode(Htmlstring)

总之,HttpContext不是万能的,当多线程调用,或是用机器模拟调用时,此时是没有HttpContext上下文的。

来自:https://www.bbsmax.com/A/KE5Q0Z0LJL/

来自:https://www.cnblogs.com/jinhaoObject/p/5342342.html

posted @ 2022-08-03 11:33  石衣_2014  阅读(237)  评论(0编辑  收藏  举报