多線程下HttpContext.Current 的問題

來源:互聯網
上載者:User

因為一個系統的查詢要做一個逾時提示的功能,想到用線程來做,結果用了線程後之前正常啟動並執行系統出錯了。

跟蹤到出錯的位置發現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的。

          

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.