Concurrent HashSet in .NET Framework?

I have the following class.

class Test{
    public HashSet<string> Data = new HashSet<string>();
}

I need to change the field “Data” from different threads, so I would like some opinions on my current thread-safe implementation.

class Test{
    public HashSet<string> Data = new HashSet<string>();

    public void Add(string Val){
            lock(Data) Data.Add(Val);
    }

    public void Remove(string Val){
            lock(Data) Data.Remove(Val);
    }
}

Is there a better solution, to go directly to field and protect it from concurrent access by multiple threads?

6 Answers
6

Leave a Comment