Let's say I want to create a collection class that is thread-safe by default.
Internally, the class has a protected List<T>
property called Values
.
For starters, it makes sense to have the class implement ICollection<T>
. Some of this interface's members are quite easy to implement; for example, Count
returns this.Values.Count
.
But implementing ICollection<T>
requires me to implement IEnumerable<T>
as well as IEnumerable
(non-generic), which is a bit tricky for a thread-safe collection.
Of course, I could always throw a NotSupportedException
on IEnumerable<T>.GetEnumerator
and IEnumerable.GetEnumerator
, but that feels like a cop-out to me.
I already have a thread-safe getValues
function which locks on Values
and returns a copy in the form of a T[]
array. So my idea was to implement GetEnumerator
by returning this.getValues().GetEnumerator()
so that the following code would actually be thread-safe:
ThreadSafeCollection coll = new ThreadSafeCollection ();
// add some items to coll
foreach (T value in coll) {
// do something with value
}
Unfortunately this implementation only seems to work for IEnumerable.GetEnumerator
, not the generic version (and so the above code throws an InvalidCastException
).
One idea I had, which seemed to work, was to cast the T[]
return value from getValues
to an IEnumerable<T>
before calling GetEnumerator
on it. An alternative would be to change getValues
to return an IEnumerable<T>
in the first place, but then for the non-generic IEnumerable.GetEnumerator
simply cast the return value from getValues
to a non-generic IEnumerable
. But I can't really decide if these approaches feel sloppy or perfectly acceptable.
In any case, does anyone have a better idea of how to go about doing this? I have heard of the .Synchronized
methods, but they seem to only be available for non-generic collections in the System.Collections
namespace. Maybe there is a generic variant of this that already exists in .NET that I simply don't know about?