[Question] Weird Dictionary problem

12/07/2011 18:07 KraHen#1
I have been struggling with this for some time now, so I decided to ask. How on earth can this :
PHP Code:

lock 
(Inventory)
{
                if (
Inventory.ContainsKey(UID))
                {
                        
Console.WriteLine("Removing key : " UID);
                        if (
Inventory[UID] != null)
                            
Inventory.Remove(UID);
                }

throw a System.Collections.Generic.KeyNotFoundException?
12/07/2011 18:35 Lateralus#2
Quote:
Originally Posted by KraHen View Post
I have been struggling with this for some time now, so I decided to ask. How on earth can this :
PHP Code:

lock 
(Inventory)
{
                if (
Inventory.ContainsKey(UID))
                {
                        
Console.WriteLine("Removing key : " UID);
                        if (
Inventory[UID] != null)
                            
Inventory.Remove(UID);
                }

throw a System.Collections.Generic.KeyNotFoundException?
Try casting to an IDictionary and locking the SyncRoot object. See, this is why using a ConcurrentDictionary in a multithreaded project owns the hell out of the generic one. Also, the test determining if the value is null is useless in this implementation (correct me if I'm wrong).
12/07/2011 18:36 Korvacs#3
You shouldnt be locking using the dictionary, you should be locking using a separate object.
12/07/2011 20:52 KraHen#4
None of these were the solutions, to be more precise these didn`t fix the error.

EDIT : Aaaand I also locked Inventory 2 times...
12/07/2011 21:40 Lateralus#5
Quote:
Originally Posted by KraHen View Post
None of these were the solutions, to be more precise these didn`t fix the error.

EDIT : Aaaand I also locked Inventory 2 times...
Haha, well, you should still be locking an object instead of the dictionary.
12/07/2011 23:37 KraHen#6
Lol I just managed to actually fix this. Turns out when I was adding to the dictionary, I used a key generated with a method which didn`t match the item`s UID, which was the key when I tried to remove from the Dictionary, and it wasn`t even the Inventory dictionary which gave me the error LOL. All I had to do is empty my items table and change the last item uid in my text file to 0 instead of 1000.

MAJOR FAIL.

No, actually locking syncroot helped besides the upper error.