4

When invoking UnionWith on a HashSet<T> in two threads I have experienced an infinite loop/deadlock when both threads are invoking AddIfNotPresent. I know that HashSet<T> is not designed to be thread-safe but looking at the implementation I couldn't find out why it would cause a deadlock (referencesource.microsoft.com).

Why would invoking UnionWith on a HashSet<T> in two threads cause a deadlock?

In other words: Why is HashSet<T> not thread safe?

Example for reference:

HashSet<Foo> points = new HashSet<Foo>();

Parallel.For(0, 2, e =>
{
    points.UnionWith(new List<Foo>() { new Foo() });
});
Jonas Nyrup
  • 2,376
  • 18
  • 25
barto90
  • 679
  • 1
  • 9
  • 27

1 Answers1

3

Through the call chain, the method may call AddIfNotPresent which in turn may call IncreaseCapacity which calls SetCapacity which in turn copies the whole internal array into a new one. That is obviously not thread safe without any synchronization measures.

Lots of other things are probably not thread safe as well, but that one should be the most obvious.

nvoigt
  • 75,013
  • 26
  • 93
  • 142