我究竟做错了什么?锁不够?
private static Readonly Hashtable sessionsTimeoutData = Hashtable.Synchronized(new Hashtable(5000));解决方法 您希望使用SyncRoot锁定,SyncRoot是同步Hashtable的方法将锁定的对象:private static voID ClearTimedoutSessions() { List keysToRemove = new List(); long Now = DateTime.Now.Ticks; lock (sessionsTimeoutData) { TimeoutData timeoutData; foreach (DictionaryEntry entry in sessionsTimeoutData) { timeoutData = (TimeoutData)entry.Value; if (Now - timeoutData.LastAccesstime > timeoutData.UserTimeoutTicks) keysToRemove.Add((ulong)entry.Key); } } foreach (ulong key in keysToRemove) sessionsTimeoutData.Remove(key); }
lock (sessionsTimeoutData.SyncRoot){ // ...}
见http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx:
总结Enumerating through a collection is
intrinsically not a thread-safe
procedure. Even when a collection is
synchronized,other threads can still
modify the collection,which causes
the enumerator to throw an exception.
To guarantee thread safety during
enumeration,you can either lock the
collection during the entire
enumeration or catch the exceptions
resulting from changes made by other
threads.The following code example shows how
to lock the collection using the
SyncRoot during the entire
enumeration:06001
以上是内存溢出为你收集整理的c# – InvalidOperationException:修改了集合 – 虽然锁定了集合全部内容,希望文章能够帮你解决c# – InvalidOperationException:修改了集合 – 虽然锁定了集合所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)