因为一个系统的查询要做一个超时提示的功能,想到用线程来做,结果用了线程后之前正常运行的系统出错了。
跟踪到出错的位置发现HttpContext.Current 为空,产生“未将对象引用到对象实例”的异常。搜索线程 HttpContext发现已经有人写了个方法可以解决问题,直接拿来用了。方法如下
- public static string MapPath(string strPath)
- {
- if (System.Web.HttpContext.Current != null)
- {
- return System.Web.HttpContext.Current.Server.MapPath(strPath);
- }
- else //非web程序引用
- {
- strPath = strPath.Replace("/", "");
- strPath = strPath.Replace("~","");
- if (strPath.StartsWith("//"))
- {
- strPath = strPath.TrimStart('//');
- }
- return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
- }
- }
自己的理解:
1.HttpContext.Current表示当前HttpRequest 对应的Context对象
httpContext.current在不同的httpRequest 中是变化的
也就是说用httpConext.current.items来保存的数据是不能跨页面传递的。
2.HttpContext.Current只能从当前正在执行的线程中返回值
3.HttpContext.Current
这个会跟Thread.CurrentContext相关,多线程切换的时候
HttpContext.Current会被替换为当前线程的Context的。