Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICollection, readonly collections, and synchronisation. Is this right?

Tags:

c#

.net-2.0

I have a custom class that implements ICollection, and this class is readonly, ie. IsReadOnly returns true (as opposed to using the readonly keyword), and all functions that would normally modify the data in the collection throw InvalidOperationException's.

Now, given such a construct, and a quick skim over the thread-safety issues when implementing ICollection (specifically ICollection.IsSynchronized and friends), I came up with this quick and dirty solution.

bool ICollection.IsSynchronised { get{ return true; } }
object ICollection.SyncRoot { get{ return new Object(); } }

Now, given the examples in MSDN, this won't cause different threads to lock properly, because they are getting different objects from SyncRoot. Given that this is a readonly collection though, is this an issue? Are there memory/GC issues with returning new Object()? Any other issues you can see with this implementation?

like image 895
Matthew Scharley Avatar asked Oct 17 '08 08:10

Matthew Scharley


2 Answers

Yes this is an issue in some cases. Even though the collection is read only and cannot be changed, the objects the collection references are not read only. Thus if the clients use the SyncRoot to perform locking they will not be thread safe when modifying the objects referenced by the collection.

I would recommend adding:

private readonly object syncRoot = new object();

to your class. Return this as the SyncRoot and you're good to go.

like image 193
Kimoz Avatar answered Oct 19 '22 19:10

Kimoz


I guess the issue would be if clients used your sync root to achieve locking of not only your collection, but something else. Supposed they cached the size of the collection - or maybe "what subset of this collection matches a predicate" - they would reasonably assume that they could use your SyncRoot to guard both your collection and their other member.

Personally I hardly use SyncRoot at all, but I think it would be sensible to always return the same thing.

like image 38
Jon Skeet Avatar answered Oct 19 '22 18:10

Jon Skeet