问题
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