背景
一直沒有意識到會話的訪問會導致會話鎖定,現在想想這樣設計是非常合理的,不過某些情況下這樣會導致同一個會話的並發訪問非常低(只能串行化),好在MS提供了機制讓我們控制這種鎖。
測試
A頁面:緩存寫入頁面
1 public partial class Session_Lock_Test : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 this.Session["Data"] = DateTime.Now; 6 7 this.Response.Write(this.Session["Data"]); 8 } 9 }
B頁面:緩存讀取頁面(長時間)
1 public partial class Session_Lock_Read_Long_Test : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 System.Threading.Thread.Sleep(5000); 6 7 this.Response.Write(this.Session["Data"].ToString() + DateTime.Now.Millisecond); 8 } 9 }
C頁面:緩存讀取頁面(短時間)
1 public partial class Session_Lock_Read_Short_Test : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 this.Response.Write(this.Session["Data"].ToString() + DateTime.Now.Millisecond); 6 } 7 }
默認的情況下,如果我們先打開B,再打開C,會發現C始終在B之后顯示。
如果修改為並行訪問呢?
在WebForm中可以這樣修改:
1 <%@ Page Language="C#" AutoEventWireup="true" EnableSessionState="ReadOnly" CodeBehind="Session_Lock_Read_Long_Test.aspx.cs" Inherits="WebFormStudy.Session_Lock_Read_Long_Test" %>
在Mvc中的可以這樣修改:
1 [SessionState(SessionStateBehavior.ReadOnly)]
備注
因為IIS Express被我弄壞了,沒法貼截圖了。
參考資料:http://msdn.microsoft.com/zh-cn/library/ms178587(v=vs.100).aspx。