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

前端 未结 2 1235
无人共我
无人共我 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:20

    There are a number of concepts here. Firstly what you have implemented correctly is a thread-safe class where no consumers of the class would need to do their own synchronisation. Therefore there is absolutely no need for you to expose the syncRoot object. In the old Collection classes the SyncRoot property was exposed because the classes were not thread-safe.

    On locking an arbitrary object and locking your inner collection there is absolutely no difference in terms of correctness or performance of the program. As long as the reference to both does not change they work just as well as parameters to the Monitor.Enter/Exit. Will your inner collection change? If no, mark it as readonly too.

    Thirdly there is the comment regarding the use of different locks based on different operations. The classic example of this is the ReaderWriterLock. You should analyse the need to use different levels of locks based on the different functionality exposed by your class.

提交回复
热议问题