Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The two pieces of code are <strong>not</strong> equivalent. The former ensures that all threads will always use the same lock object. The latter locks a lazily-initialized object, and there is absolutely nothing preventing multiple instantiations of your <code>_instance</code> dictionary, resulting in contents being lost.</p> <p>What is the purpose of the lock? Does the serve a purpose other than to guarantee single-initialization of the dictionary? Ignoring that it fails to accomplish this in the second example, if that is its sole intended purpose, then you may consider simply using the <code>Lazy&lt;T&gt;</code> class or a double-check locking pattern.</p> <p>But since this is a static member (and does not appear to capture outer generic parameters), it will presumably only be instantiated once per AppDomain. In that case, just mark it as <code>readonly</code> and initialize it in the declaration. You're probably not saving much this way.</p> <p>Since you are concerned with best practices: you should <em>never</em> use the <code>lock</code> construct on a mutable value; this goes for both static and instance fields, as well as locals. It is <em>especially</em> bad practice to lock on a <em>volatile</em> field, as the presence of that keyword indicates that you <em>expect</em> the underlying value to change. If you're going to lock on a field, it should almost always be a <code>readonly</code> field. It's also considered bad practice to lock on a method result; that applies to properties too, as properties are effectively a pair of specially-named accessor methods.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload