What is the SyncRoot property in ICollection interface? Why should we lock it? I know we should lock a reference type before using it in multi threading, but why we lock SyncRoot?
Printable View
What is the SyncRoot property in ICollection interface? Why should we lock it? I know we should lock a reference type before using it in multi threading, but why we lock SyncRoot?
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.
http://msdn2.microsoft.com/en-us/lib....syncroot.aspx
I knew this exactly. But why we don't lock the collection itself but one of its properties?Quote:
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.
[edit]
I will read the link.
No it didn't help. I had read it.
The collection itself is not necessarily the only object that refers to the controlled sequence. Consider ArrayList.GetRange, which returns a view of a part of an ArrayList. Consider that collections might have similar things to Java's Collections.unmodiable*() methods, which return read-only views of collections. All these are different objects, but share an object sequence. They also share the SyncRoot, so locking on the SyncRoot guarantees that nobody interferes with your work, even if he's not accessing the sequence through the same object.
Can you explain more, please?