Click here to Skip to main content
15,918,050 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I publish a WebAPI solution, got a trouble about the Dictionary. when i remove the dictionary key, the program throw a exception,"Value cannot be null. Parameter name: key", could you help me?

C#
private static Dictionary<string, int> _dics = new Dictionary<string, int>() ;

   public TestController()
   {
       if (_dics.Count == 0)
       {
           _dics.Add("test1", 1);
           _dics.Add("test2", 2);
           _dics.Add("test3", 3);
           _dics.Add("test4", 4);
       }
   }

  var removes = _dics.Select(s => s.Key).ToArray();
            foreach (var item in removes)
            {
              _dics.Remove(item);
            }
Posted
Comments
Thomas Daniels 22-Jul-15 6:11am    
Well, it means that the parameter of Remove is null, but I cannot see why this would happen here, and I cannot reproduce it. Are you sure the error happens in this part of your code?
Wendelius 22-Jul-15 6:15am    
The program fragment you posted works just fine. Perhaps the real situation is different?
F-ES Sitecore 22-Jul-15 6:31am    
I agree with Praveen, this is likely to be a multi-thread issue due to the static nature of your dictionary. If you want to empty it then just call the Clear method. Or if you are doing other things you have omitted for brevity then introduce locking around code that manipulates the dictionary, but this will hamper performance.

1 solution

If it's a WebAPI, then static Dictionary creating a problem. As it will be shared with multiple objects. So if some other object removed "test1" key already, some other objects will try to remove the same and will get error.
 
Share this answer
 
Comments
Praveen Kumar Upadhyay 23-Jul-15 2:40am    
Thank you guys for upvoting. OP please accept solution if you are agree too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900