一直在用Session,對Session鎖並沒有太多的關注,可能是平時沒有注意。前段時間突然發現,一個Ajax Get請求,直接訪問地址,只需要幾十ms,但是在頁面中加載,卻需要2s。最后定位到Session的問題。
具體的內容我在園里看了下別人的文章:http://blog.csdn.net/paolei/article/details/38052129
不過,也發現了一些問題。
比如,這個例子:
后端:
public class MyController : Controller { // GET: My public ActionResult Index() { return View(); } [HttpGet] public string GetTest1() { Thread.Sleep(1000); return "GetTest1"; } [HttpGet] public string GetTest2() { return "GetTest2"; } }
前端:
$.get("GetTest1", function (resp) { console.log(resp); // server response }); $.get("GetTest2", function (resp) { console.log(resp); // server response });
直接使用上面的代碼,沒有訪問過Session,代碼默認不進行Session鎖,運行結果:
GetTest2
GetTest1
當在Controller中寫Session后:
public ActionResult Index() { Session["A"] = "A"; return View(); }
運行結果:
GetTest1
GetTest2
然后按上文在Controller前加:[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)],再次運行,發現結果是一樣的,說明ReadOnly是無效的。
其實也是,雖然是ReadOnly,但是代碼中還是寫了,這和ReadOnly顯然是矛盾的,但是代碼並不會報錯,只是這個屬性無效了。
后來,改成:[SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]
這時再運行,就直接報錯了。
最后總結了一下,只要Controller中有Session的寫,無論Controller前的SessionStateBehavior是什么,都會認為Session是可寫的,會進行Session鎖。 所以,如果真的對Ajax並發性能要求比較高的話,就不能用Session了吧。 所以,覺得SessionStateBehavior這個屬性有點雞肋呀。本人淺見,如果有高手希望指點一二。
后來,我對自己的應用想到了一個不是辦法的辦法,把另外一個Ajax加載比較慢的,使用timeout 20ms,這個是調用一個復雜的計算加載待辦數的,另一個是加載頁面列表數據,顯然,用戶一開始最想先看到列表數據。