锁内的InvalidOperationException [英] InvalidOperationException within Lock
问题描述
我在单例类中有一个集合,称为类型为SynchronizedCollection< RemoteMachine.Node>的_connectedNodes.每次访问此集合的单次调用都包含在一个锁定语句中,该语句与下面的代码段相同.
I have a collection in a singleton class, called _connectedNodes of type SynchronizedCollection<RemoteMachine.Node>. EVERY single call to access this collection is wrapped in a lock statement identical to the one in the snippet below.
lock (_instance._connectedNodes.SyncRoot)
{
foreach (RemoteMachine.Node node in _instance._connectedNodes)
{
if (node.Connection.State == RemoteMachine.ConnectionState.Normal)
node.Connection.Send(protoMessage.ToString());
}
}
这段代码基本上是使用异步套接字将消息发送到一组连接的节点.
This code is basically using async sockets to send messages to a group of connected nodes. How could I have had a 'collection was modified' error within this snippet?
推荐答案
最有可能是您要添加或删除集合_instance._connectedNodes的错误?否则并没有锁定它.我建议您在处理此集合的其他位置(添加和删除)使用相同的锁定代码.
Most likely you are adding or removing to the collection _instance._connectedNodes somewhere else and not locking that. I would suggest you use the same lock code in other spots where you are working with this collection (for adding and deleting).
这篇关于锁内的InvalidOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!