The concurrent collections were intended as a means of safely modifying the collection itself; not the items. You will have to add your own synchronization primitives to the Cell
class. If the outer and inner List
instances themselves will remain unchanged there is no need to apply synchronization to them.
You mentioned that you will have many readers, but only one writer. That is an incredibly important detail. It means that any lock-free synchronization strategies become dramatically easier to implement. However, I do not encourage going down that route as it would still be quite difficult to get right. But, it could also mean that the ReaderWriterLockSlim
might perform better than a lock
.
You will have to experiment with both to see which one provides the best balance of maintainability and efficiency. My hunch is that you will find a traditional lock
will perform faster despite having multiple readers and a single writer, but it is worth testing. It is certainly a lot easier on the fingers when typing out the code.
Here is sample code for both.
public class Cell
{
private object m_LockObject = new object();
public object ReadMyState()
{
lock (m_LockObject)
{
// Return the data here.
}
}
public void ChangeMyState()
{
lock (m_LockObject)
{
// Make your changes here.
}
}
}
and
public class Cell
{
private ReaderWriterLockSlim m_LockObject = new ReaderWriterLockSlim();
public object ReadMyState()
{
m_LockObject.EnterReadLock();
try
{
// Return the data here.
}
finally
{
m_LockObject.ExitReadLock();
}
}
public void ChangeMyState()
{
m_LockObject.EnterWriteLock();
try
{
// Make your changes here.
}
finally
{
m_LockObject.ExitWriteLock();
}
}
}