I'm creating a custom collection that encapsulates a ConcurrentDictionary. I found a lot of information on encapsulating/inheriting from a generic collection but nothing specific to concurrent collections. Here is a code snippet of my base case, followed by some general questions.
class ItemCollection
{
private ConcurrentDictionary<string, Item> Collection;
public ItemCollection() { Collection = new ConcurrentDictionary<string, Item>(); }
public bool TryAdd(string webId, string name) { return Collection.TryAdd(webId, new Item(name)); }
public bool TryAdd(string webId, Item item) { return Collection.TryAdd(webId, item); }
public bool TryUpdate(KeyValuePair<string, Item> entry, Data data)
{
Item newItem = entry.Value;
newItem.AddData(data);
return Collection.TryUpdate(entry.Key, newItem, entry.Value);
}
}
- Is encapsulating concurrent collections in this manner acceptable, or is this moving into the realm of creating your own thread-safe collection from a generic collection?
- Is the custom collection thread-safe?
- Is inheriting a concurrent collection ever acceptable? Like so
class ItemCollection : ConcurrentDictionary<string, Item>
and if so what are some guidelines, similar to this for inheriting from non-concurrent collections. - How do you implement forwarding methods for methods like Select? I tried a series of variations like the following but can't get it to work:
public IEnumerable<TResult> Select<ItemCollection, TResult>(this ItemCollection source, Func<KeyValuePair<string, Item>, TResult> selector) { return Collection.Select(selector); }
If I inherit the ConcurrentDictionary it results in an implementation like