因為一個系統的查詢要做一個逾時提示的功能,想到用線程來做,結果用了線程後之前正常啟動並執行系統出錯了。
跟蹤到出錯的位置發現HttpContext.Current 為空白,產生“未將對象引用到對象執行個體”的異常。搜尋線程 HttpContext發現已經有人寫了個方法可以解決問題,直接拿來用了。方法如下
public static string MapPath(string strPath)<br />{<br /> if (System.Web.HttpContext.Current != null)<br /> {<br /> return System.Web.HttpContext.Current.Server.MapPath(strPath);<br /> }<br /> else //非web程式引用<br /> {<br /> strPath = strPath.Replace("/", "");<br /> strPath = strPath.Replace("~","");<br /> if (strPath.StartsWith("//"))<br /> {<br /> strPath = strPath.TrimStart('//');<br /> }<br /> return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);<br /> }<br />}<br />
自己的理解:
1.HttpContext.Current表示當前HttpRequest 對應的Context對象
httpContext.current在不同的httpRequest 中是變化的
也就是說用httpConext.current.items來儲存的資料是不能跨頁面傳遞的。
2.HttpContext.Current只能從當前正在執行的線程中傳回值
3.HttpContext.Current
這個會跟Thread.CurrentContext相關,多線程切換的時候
HttpContext.Current會被替換為當前線程的Context的。