gpt4 book ai didi

c# - 无效操作异常 : Collection was modified - although locking the collection

转载 作者:太空狗 更新时间:2023-10-29 20:08:34 24 4
gpt4 key购买 nike

我有一个同步哈希表,我会定期从中删除一些条目。多个线程运行此代码。所以我锁定了整个 foreach,但有时我仍然会收到 InvalidOperationException: Collection was modified ... at Hashtable.HashtableEnumerator.MoveNext() - 即在 foreach 循环中。我究竟做错了什么?锁定还不够吗?

private static readonly Hashtable sessionsTimeoutData = Hashtable.Synchronized(new Hashtable(5000));<p></p>

<p>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);
}</p>

最佳答案

您想使用 SyncRoot 进行锁定,这是同步 Hashtable 的方法将锁定的对象:

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:

Hashtable myCollection = new Hashtable();
lock(myCollection.SyncRoot)
{
foreach (object item in myCollection)
{
// Insert your code here.
}
}

关于c# - 无效操作异常 : Collection was modified - although locking the collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com