HashSet<T>
is not thread safe, so the second option (using Parallel.ForEach
) will likely cause bugs. It should definitely be avoided.
The best option is likely to just build the hashset directly from the results:
var myHashSet = new HashSet<int>(IDs);
Note that this only works if the HashSet
is only intended to contain the items from this collection. If you're adding to an existing HashSet<T>
, a foreach
(your first option) is likely the best option.