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() });
});