I read something about the SyncRoot pattern as a general rule to avoid deadlocks. And reading a question of a few years ago (see this link), I think I understand that some uses of this pattern may be incorrect. In particular, I focused on the following sentences from this topic:
You’ll notice a SyncRoot property on many of the Collections in System.Collections. In retrospeced, I think this property was a mistake... Rest assured we will not make the same mistake as we build the generic versions of these collections.
In fact, for example, List<T>
class doesn't implements SyncRoot
property, or more correctly it is implemented explicitly (see this answer), so you must cast to ICollection
in order to use it. But this comment argues that making a private SyncRoot
field public is as bad practice as locking on this
(see this answer), as also confirmed in this comment.
So, if I understand correctly, when I implement a non thread-safe data structure, since it could be used in a multithreaded context, I should not (actually, I must not) provide the SyncRoot
property. But I should leave the developer (who will use this data structure) with the task of associating it with a private SyncRoot object as in the following sample code.
public class A
{
private MyNonThreadSafeDataStructure list;
private readonly object list_SyncRoot = new object;
public Method1()
{
lock(list_SyncRoot)
{
// access to "list" private field
}
}
public Method2()
{
lock(list_SyncRoot)
{
// access to "list" private field
}
}
}
In summary, I understood that the best practices for synchronization/locking should be as follows:
- Any private SyncRoot objects should not be exposed through a public property; in other words, a custom data structure should not provide a public
SyncRoot
property (see also this comment). - In general, it is not mandatory to use private objects for locking (see this answer).
- If a class has multiple sets of operations that need to be synchronised, but not with each other, it should have multiple private SyncRoot objects (see this comment).
Is what written above the proper use of this pattern?