Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the difference between locking the specified object and locking a secondary object?
    text
    copied!<p>I was recently asked by a friend of mine who's just starting to play around with threading what the difference between using a secondary object purely for the purpose of locking or just locking the object you're referencing is. I had to admit that I had no idea, can anyone tell me? I will try and demonstrate with a couple of code snippets:</p> <p>First method:</p> <pre><code>List&lt;string&gt; data = new List&lt;string&gt;(); object datalock = new object(); void main() { lock(datalock) { if (data.contains("SomeSearchString")) { //Do something with the data and then remove it } } } </code></pre> <p>Second method:</p> <pre><code>List&lt;string&gt; data = new List&lt;string&gt;(); void main() { lock(data) { if (data.contains("SomeSearchString")) { //Do something with the data and then remove it } } } </code></pre> <p>Is there a significant difference or is this down to personal coding style? If there is a significant difference, can anyone explain what it is?</p> <p>I did come across another question [<a href="https://stackoverflow.com/questions/230716/difference-between-locklocker-and-lockvariablewhichiamusing">Difference between lock(locker) and lock(variable_which_I_am_using)</a>] in which the answer implied that both of these are equivalent, but if that's the case, which would be the best to use and why?</p> <p>I've seen a number of examples scattered around the net, I tend to use the first method as a matter of personal choice, but I wondered what the merits of using the second method would be.</p>
 

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