在线程编程时能够为我们的性能提高不少,但是线程不是请求所以请求上下文我们就不能够用到!我在编程时遇到的几个地方留下个映像,同时也希望给不知道的同志们留个纪念!!! 1.缓存(Cache):我们通常会从System.Web.HttpContext.Current.Cache获取,但是在线程中我们所得到的HttpContext.Current为null,所以我们得通过System.Web.HttpRuntime.Cache获得缓存实例,我们可以封装一个方法,这样我们就可以不用管他是在哪里都可以调用当前缓存了。代码如下: 1 public class Cacher 2 { 3 private Cacher() { } 4 5 private static readonly Cache cache; 6 7 static Cacher() { 8 HttpContext context = HttpContext.Current; 9 if (context == null ) 10 cache = context.Cache; 11 else 12 cache = HttpRuntime.Cache; 13 } 14 } 2.获取文件的物理路径:通常我们会用System.Web.HttpContext.Current.Request来获取当前的物理等有关路径或URL,通过System.Web.HttpContext.Current.Server.MapPath方法来获取当前文件或目录的物理路径。和上面一样在线程中这是解决不了问题的,我们可以通过应用程序域(System.AppDomain.CurrentDomain.BaseDirectory)来获得根目录。
1 public static string RootPath() { 2 return RootPath( " / " ); 3 } 4 5 public static string RootPath( string filePath) 6 { 7 string rootPath = AppDomain.CurrentDomain.BaseDirectory; 8 string separator = Path.DirectorySeparatorChar.ToString(); 9 rootPath = rootPath.Replace( " / " , separator); 10 if (filePath != null ) 11 { 12 filePath = filePath.Replace( " / " , separator); 13 if (((filePath.Length > 0 ) && filePath.StartsWith(separator)) && rootPath.EndsWith(separator)) 14 { 15 rootPath = rootPath + filePath.Substring( 1 ); 16 } 17 else 18 { 19 rootPath = rootPath + filePath; 20 } 21 } 22 return rootPath; 23 } 24 25 public string PhysicalPath( string path) 26 { 27 return (RootPath().TrimEnd( new char [] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar.ToString() + path.TrimStart( new char [] { Path.DirectorySeparatorChar })); 28 } 29 30 public string MapPath( string path) 31 { 32 HttpContext context = HttpContext.Current; 33 if (context != null ) 34 { 35 return context.Server.MapPath(path); 36 } 37 return PhysicalPath(path.Replace( " / " , Path.DirectorySeparatorChar.ToString()).Replace( " ~ " , "" )); 38 } OK,暂时先逮住这两个家伙,以后发现了再补上!!!
本文转自网魂小兵博客园博客,原文链接:http://www.cnblogs.com/xdotnet/archive/2007/06/25/aspnet_threading_httpcontext.html,如需转载请自行联系原作者