線上程編程時能夠為我們的效能提高不少,但是線程不是請求所以請求上下文我們就不能夠用到!我在編程時遇到的幾個地方留下個映像,同時也希望給不知道的同志們留個紀念!!!
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,暫時先逮住這兩個傢伙,以後發現了再補上!!!