多线程中使用HttpContext.Current为null的解决办法

记一次项目中遇到的问题。

最近在实现一个商品库自动同步功能,使用的是Quartz.Net,然后每天凌晨执行一次,执行的时候,会去自动的遍历文件夹下是否有新增的文件,如果有,则获取这些文件,自动同步到七牛云空间上。

在这其中,就有用到HttpContext.Current.Server.MapPath() 将相对路径转为物理路径。

直接调用方法,是正常的,但是在Quartz.Net执行的时候,用的是多线程,所以导致HttpContext.Current获取到的是null。

通过百度,查询到的原因如下:

因为多线程情况下,当前线程可能并非http请求处理线程,根本没发生请求,所以无法获取到HttpContext就是null.

解决方法可以采用这种:

public static string MapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);//有http请求
            }
            else //非web程序引用         
            {
                strPath = strPath.Replace("/", "\");
                if (strPath.StartsWith("\"))
                {
                    //strPath = strPath.Substring(strPath.IndexOf('\', 1)).TrimStart('\');                            strPath = strPath.TrimStart('\');               
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
原文地址:https://www.cnblogs.com/liuping666/p/15127210.html