0

Assume that i have the hashset below

   HashSet<string> hsWaitingToBeFetched = new HashSet<string>();

Now i am doing multithreading programming so i have to lock this in order to sync objects

I can lock this with both way are there any performance difference ?

private Object lockHashset = new Object();
lock(lockHashset)
{
// do stuff here
}

or

lock(hsWaitingToBeFetched)
{
// do stuff here
}
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • If you need to know which will be more performant, you should consider trying both and measuring. Note that choosing which object to lock on is more of an issue from a *program correctness* standpoint, rather than a performance standpoint. – dlev May 20 '13 at 21:01
  • 1
    Is the hash set private? And is there ever a situation in which the hash set *itself* changes? That is, do you change the value of the variable that refers to the set, or do you merely change the contents of the set? – Eric Lippert May 20 '13 at 21:56
  • You could use a `ConcurrentDictionary` instead, simply ignore the `Value` – Tim Schmelter Oct 26 '18 at 07:58

1 Answers1

3

There will be no performance difference1.. the semantic difference will be if some other code also locks on the HashSet if it is exposed.

I think it is more clear to use a separate lock object in such a case:

  1. Clearer intent - depends on scenario
  2. Can hide lock object (private) but expose HashSet This should be disregarded without very careful consideration - locking only for (private) updating a (public) HashSet is not correctly synchronized.
  3. Avoid surprises if a type locks on itself
  4. Usable even when re-assigning the HashSet member

However, because a separate lock object doesn't lock on the HashSet, if something else expects that it does ..


1 The new lock object creation cost is ignorable. The CLR enters a monitor in the same manner for both cases described.

user2246674
  • 7,621
  • 25
  • 28
  • I don't understand point #2. If you expose the hash set and not the lock object then how is the code you expose it to going to use it safely? – Eric Lippert May 20 '13 at 21:55
  • @EricLippert Thanks for the challenge - I can't come up with any non-convoluted use-cases and have struck out the item. (I was *sure* I had a good point in mind when I wrote it, but on retrospection it seems misguided ..) – user2246674 May 20 '13 at 22:18
  • The usual situation where you want to both expose an object and have a lock associated with it is hinted at in your third item: when the object that is logically locked is of type `Type`. It can be very difficult to *not* expose a type, and therefore the locked object should be private to ensure that *only code inside the type locks itself*. – Eric Lippert May 20 '13 at 22:33