前言
最近將動力起航的站內搜索功能進行了改造,使用了Lucene.Net+盤古分詞實現了完整的站內搜索功能(此功能改造將另開章節跟大家講講,需要源碼的可以留下郵箱,下一章節也會貼出來),本章主要講講在改造過程中使用多線程使用HttpContext.Current為null的問題而總結的幾個方法,希望大家多多提意見和建議,這樣我才能提高,深感閉門造車的苦惱,希望向園子里的大牛們學習!
問題一:多線程下獲取文件絕對路徑
當我們使用HttpContext.Current.Server.MapPath(strPath)獲取絕對路徑時HttpContext.Current為null,解決辦法如下:
#region 獲得當前絕對路徑 /// <summary> /// 獲得當前絕對路徑 /// </summary> /// <param name="strPath">指定的路徑</param> /// <returns>絕對路徑</returns> public static string GetMapPath(string strPath) { if (strPath.ToLower().StartsWith("http://")) { return strPath; } if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\") || strPath.StartsWith("~")) { strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } } #endregion
問題二:多線程下獲取緩存問題
多線程下使用HttpContext.Current.Cache.Get(key)獲取緩存時HttpContext.Current為null,解決辦法如下:
HttpRuntime.Cache.Get(key);
從MSDN上的解釋可以看出,HttpRuntime.Cache是應用程序級別的,而HttpContext.Current.Cache是針對當前WEB上下文定義的。
然而,實際上,這二個都是調用的同一個對象,不同的是:HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。
而HttpContext則只能用在WEB中。
因此,在可能的情況下,我們盡可能使用HttpRuntime(然而,在不同應用程序之間如何調用也是一個問題)。
具體的大家可以參考此博文:http://www.cnblogs.com/McJeremy/archive/2008/12/01/1344660.html
問題三:多線程下使用Html轉碼問題
多線程下使用HttpContext.Current.Server.HtmlEncode(Htmlstring)轉碼HttpContext.Current為null,解決辦法如下:
HttpUtility.HtmlEncode(Htmlstring)
結束語
從以上可以看出,在可能的情況下,我們應該盡可能的使用應用程序級別的方法,這樣避免不必要的錯誤!