System.ArgumentException occurred

只谈情不闲聊 提交于 2019-12-25 01:48:38

问题


I'm getting a strange behavior. This is the code:

...
private Object lockobj = new Object();
private Dictionary<String, BasicTagBean> toVerifyTags = null;

public void verifyTags(List<BasicTagBean> tags)
{
    System.Diagnostics.Debug.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId);
    lock (lockobj)
    {
        foreach (BasicTagBean tag in tags)
        {
            if (!alreadyVerified.ContainsKey(tag.EPC))
            {
                toVerifyTags.Add(tag.EPC, tag);
            }
        }
    }
...

Sometimes I got this exception

'System.ArgumentException' occurred in mscorlib.dll

at this line of code:

toVerifyTags.Add(tag.EPC, tag);

the exception refer to wrong add of an already existing element into collection, but I check this. Maybe a thread problem but application output shows always the same thread id. I'm using c# pocketpc version 3.5.


回答1:


The exception seems to tell you that the key you are trying to add in toVerifyTags already exists. You weren't checking if the key already existed in the right dictionary.

public void verifyTags(List<BasicTagBean> tags)
{
    System.Diagnostics.Debug.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId);
    lock (lockobj)
    {
        foreach (BasicTagBean tag in tags)
        {
            if (!toVerifyTags.ContainsKey(tag.EPC))
            {
                toVerifyTags.Add(tag.EPC, tag);
            }
        }
    }


来源:https://stackoverflow.com/questions/24613246/system-argumentexception-occurred

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!