Best C# solution for multithreaded threadsafe read/write locking?

前端 未结 8 790
无人共我
无人共我 2021-01-01 05:08

What is the safest (and shortest) way do lock read/write access to static members in a multithreaded environment in C#?

Is it possible to do the thread

8条回答
  •  天命终不由人
    2021-01-01 05:47

    Several others have already explained how to use the lock keyword with a private lock object, so I will just add this:

    Be aware that even if you lock inside each method in your type, calling more than one method in a sequence can not be considered atomic. For example if you're implementing a dictionary and your interface has a Contains method and an Add method, calling Contains followed by Add will not be atomic. Someone could modify the dictionary between the calls to Contains and Add - i.e. there's a race condition. To work around this you would have to change the interface and offer a method like AddIfNotPresent (or similar) which encapsulates both the checking and the modification as a single action.

    Jared Par has an excellent blog post on the topic (be sure to read the comments as well).

提交回复
热议问题