您的位置:首页 > 理论基础 > 计算机网络

线程编程中用到HttpContext.Current的方法封装

2007-06-25 21:42 337 查看
在线程编程时能够为我们的性能提高不少,但是线程不是请求所以请求上下文我们就不能够用到!我在编程时遇到的几个地方留下个映像,同时也希望给不知道的同志们留个纪念!!!

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)
cache = context.Cache;
else
cache = HttpRuntime.Cache;
}
}

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);
if (filePath != null)
{
filePath = filePath.Replace("/", separator);
if (((filePath.Length > 0) && filePath.StartsWith(separator)) && rootPath.EndsWith(separator))
{
rootPath = rootPath + filePath.Substring(1);
}
else
{
rootPath = rootPath + filePath;
}
}
return rootPath;
}

public string PhysicalPath(string path)
{
return (RootPath().TrimEnd(new char[] { Path.DirectorySeparatorChar })
+ Path.DirectorySeparatorChar.ToString() + path.TrimStart(new char[] { Path.DirectorySeparatorChar }));
}

public string MapPath(string path)
{
HttpContext context = HttpContext.Current;
if (context != null)
{
return context.Server.MapPath(path);
}
return PhysicalPath(path.Replace("/", Path.DirectorySeparatorChar.ToString()).Replace("~", ""));
}

OK,暂时先逮住这两个家伙,以后发现了再补上!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: