2

I want to perform some action in an other thread if a new key\value pair is added to static dictionary. One naïve method is to do polling at frequent intervals and check if ContainsKey(givenKey), but I want to do even more quicker instead of delay in polling.

Rahul Sundar
  • 480
  • 8
  • 26
  • 3
    You might want to see http://stackoverflow.com/questions/5663395/net-observabledictionary. I don't believe there's anything built into the framework. (There are lots of third party implementations though.) – Jon Skeet Jan 20 '15 at 06:57
  • Thanks Jon. We end up creating custom dictionary to get done this simple thing. Would be good if built into framework! – Rahul Sundar Jan 20 '15 at 07:03
  • @RahulSundar oh, i`ve read your comment to late ): But maybe i provide some more information :) – BendEg Jan 20 '15 at 07:37

1 Answers1

10

You have to create your own Dictionary. Best practice would be:

public enum Type
{
    AddItem,
    RemoveItem
}

public class DictChangedEventArgs<K, V> : EventArgs
{
    public Type Type
    {
        get;
        set;
    }

    public K Key
    {
        get;
        set;
    }

    public V Value
    {
        get;
        set;
    }
}

public class OwnDict<K, V> : IDictionary<K, V>
{
    public delegate void DictionaryChanged(object sender, DictChangedEventArgs<K, V> e);

    public event DictionaryChanged OnDictionaryChanged;

    private IDictionary<K, V> innerDict;

    public OwnDict()
    {
        innerDict = new Dictionary<K, V>();
    }

    public void Add(K key, V value)
    {
        if (OnDictionaryChanged != null)
        {
            OnDictionaryChanged(this, new DictChangedEventArgs<K, V>() { Type = Type.AddItem, Key = key, Value = value });
        }

        innerDict.Add(key, value);
    }

    // ...
    // ...
}

Now you are free to create event for Before-Add-Item, After-Add-Item. You can also add some Handled parameter to your DictChangedEventArgs-Class to prevent adding a special item. You can also decide to work with the Type-Enum or create an own event for every action.

But be sure, you have to implement all methods from IDictionary, but this should be very easy.

BendEg
  • 20,098
  • 17
  • 57
  • 131
  • 1
    I see that you raise the event before you add the item to the dictionary, I believe this would then constitute a better naming convention of "PreviewChange" or something synonymously equivalent. Good answer though! +1 – Krythic Nov 12 '17 at 23:45
  • @Krythic yeah, that is true. Even better would be both. So that it would be possible to cancel adding by using the event args of the ..Preview event. – BendEg May 18 '20 at 06:42
  • 1
    A few years later...been busy, my dude? Lol. – Krythic May 18 '20 at 23:16