views:

439

answers:

2

Hi there.

I got a little problem. Sometimes, when I try to call the following code, the remove methods throw an exception with the message "the key is not present in the dictionary".

private Dictionary<IPAddress, ARPHostEntry> dIPHostTable;
private Dictionary<MACAddress, ARPHostEntry> dMACHostTable;

public HostTable()
{
    dIPHostTable = new Dictionary<IPAddress, ARPHostEntry>();
    dMACHostTable = new Dictionary<MACAddress, ARPHostEntry>();
}

public void AddHost(ARPHostEntry arphEntry)
{
    lock (dMACHostTable)
    {
        if (dMACHostTable.ContainsKey(arphEntry.MAC))
        {
            dMACHostTable.Remove(arphEntry.MAC);
        }
        dMACHostTable.Add(arphEntry.MAC, arphEntry);
    }
    lock (dIPHostTable)
    {
        if (dIPHostTable.ContainsKey(arphEntry.IP))
        {
            dIPHostTable.Remove(arphEntry.IP);
        }
        dIPHostTable.Add(arphEntry.IP, arphEntry);
    }
}

The class ARPHostEntry is a simple calss which holds an IP-Address and an associated MAC-Address where both fiels in this class are read-only. The program is multi-threaded, but I lock the dictionarys in this class every time I use them.

I am helpless. Why do this exceptions occour?

with best regards

+2  A: 

The Remove method shouldn't throw such exception, it should return false if key not found (See here). Instead of removing and adding, why don't you try updating the value of the key?

o.k.w
O_O. Okay, i will re-check this. Strange. And I will try to update only the value. Thanks.
Emiswelt
@Emiswelt: Do let us know if it works (or not).
o.k.w
I'm probably a little late but I fixed it the way you suggested. Together with a cleaner multihtreading-model (ISyncrhonizeInvoke) in the calling class it works now.
Emiswelt
A: 

It's unclear from your example if you're truly sharing the host tables across threads. Shouldn't the private host tables also be static?

ebpower
No, I need multiple instances of this class for multiple network interfaces which are shared with many other objecty implementing higher layers and many threads.
Emiswelt