Note that there are some explanatory texts on larger screens.

plurals
  1. POIs locking on the requested object a bad idea?
    text
    copied!<p>Most advice on thread safety involves some variation of the following pattern:</p> <pre><code>public class Thing { private readonly object padlock = new object(); private IDictionary stuff, andNonsense; public Thing() { this.stuff = new Dictionary(); this.andNonsense = new Dictionary(); } public IDictionary Stuff { get { lock (this.padlock) { if (this.stuff.Count == 0) this.stuff = this.SomeExpensiveOperation(); return this.stuff; } } } public IDictionary AndNonsense { get { lock (this.padlock) { if (this.andNonsense.Count == 0) this.andNonsense = this.AnotherExpensiveOperation(); return this.andNonsense; } } } // Rest of class... } </code></pre> <p>In cases where the get operations are expensive and unrelated, a single locking object is unsuitable because a call to <code>Stuff</code> would block all calls to <code>AndNonsense</code>, degrading performance. And rather than create a lock object for each call, wouldn't it be better to acquire the lock on the member itself (assuming it is not something that implements <code>SyncRoot</code> or somesuch for that purpose? For example:</p> <pre><code>public IDictionary Stuff { get { lock (this.stuff) { if (this.stuff.Count == 0) this.stuff = this.SomeExpensiveOperation(); return this.stuff; } } } </code></pre> <p>Strangely, I have never seen this approach recommended or warned against. Am I missing something obvious?</p> <p><strong>EDIT 24 May 2010</strong></p> <blockquote> <p>I have made some extensive changes because I really borked my example. Serves me right for trying to simplify the example too much for clarity.</p> <p>Summary of edits:</p> <ul> <li>Locking object in first example is no longer static (my original example was from a static class).</li> <li>Fields/properties no longer a string, and initialised in constructor so never null.</li> <li>Moved return statement inside the <code>lock{...}</code> block.</li> </ul> </blockquote>
 

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