1. 程式人生 > >多執行緒Session賦值,可能存在Index was outside the bounds of the array.

多執行緒Session賦值,可能存在Index was outside the bounds of the array.

2018/11/01 碰到了Session賦值導致整個網站崩潰了,檢查日誌,發現是索引越界

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.ArrayList.Add(Object value)
   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
   at System.Web.SessionState.SessionStateItemCollection.set_Item(String name, Object value)
   at LeXinMailBase.SessionHelper.SetSession(String UserID, String key, String value)
   at LeXinMailServer.MailBaseServer.InitSetSession(String UserNo)

使用Session[UserID + key] = value;乍一看根本不存在索引問題

即使Sessiong內部採用ArrayList,ArrayList.Add也沒有索引問題呀

然後就到網上找看是不是有IIS對Session個數是不是有限制,又自己測試,發現Session數量達到1千萬數量也沒有存在越界問題,最後是存的太多導致記憶體溢位報錯,看來不是Session個數限制

然後有找ArrayList是否存在索引越界問題,找到關於多執行緒操作碰到ArrayList越界說法,

https://blog.csdn.net/u010010428/article/details/51258783

想來Session是採用Arraylist,估計也類似會存在越界

於是給session賦值加了方法鎖,然後等待後續觀察

  lock (SessionLock)
{
Session[UserID + key] = value;
}