Some clarification on the SyncRoot pattern: what is the correct way to use this pattern?

前端 未结 2 1254
无人共我
无人共我 2021-01-12 08:03

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 th

2条回答
  •  醉酒成梦
    2021-01-12 08:21

    I would avoid adding a SyncRoot property to the type that I design, here are the reasons:

    • Users of my type may need to use different synchronisation mechanism, for example Mutex, or ReaderWriterLock or ReaderWriterLockSlim etc

    • The type becomes fatter: its responsibility becomes more scattered. Why would I add support for explicit multithreading locking and no support for other fluff? I would force the user to follow only one practise, which may not be the best solution in all cases

    • I would need to implement the property correctly (no returning this or typeof(MyClass)), i.e. this is wrong:

      public object SyncRoot {get {return this;}}
      

    I would also avoid using SyncRoot property from the .NET framework types. If I need to make a type w/o SyncRoot property threadsafe I will use one locking pattern, and if a type has this property I will still not opt for locking on SyncRoot. This makes my code style consistent and easier to read/maintain.

提交回复
热议问题