Garrett
Garrett

Reputation: 155

EXE throws errors when DEBUG does not

The program has a form that pops up, you enter text in a few fields, then press close. Upon close the information entered is saved to a class newItem.

When I press F5 to debug my program everything works fine. But when I run the executable from my debug folder I get this error.

System.ArgumentException: An item with the same key has already been added.
    At.... line 168

Here's the code.

if (!LoadedItem.Contains(newItem))
{
    LoadedItem.Add(newItem);
}

I placed a break point, stepped through the code, everything seems to go as it should. It skips over if LoadedItem already has newItem in it. But for some reason it appears to ignore the if statement in the .exe.

Please let me know if there is more information you require.

I would appreciate any help, for the life of me I can't figure out why this is happening.

Upvotes: 0

Views: 137

Answers (2)

Marcelo De Zen
Marcelo De Zen

Reputation: 9497

Lock LoadedItem should work

lock(LoadedItem) {
    if (!LoadedItem.Contains(newItem))
       LoadedItem.Add(newItem);
}

Note that you have to use lock on every point in the code where you write and read to/from LoadedItem.

If you read more than write, use ReaderWriterLockSlim to better performance.

If you're using .Net4 you can use some of the collections in the System.Collections.Concurrent namespace.

Upvotes: 3

ddyer
ddyer

Reputation: 1788

This sounds like a threading problem. Make sure LoadedItem and NewItem are locally bound variables, so the two references are guaranteed to be the same object.

For debugging purposes, Replace "Contains" and "Add" with a wrapper functions whose behavior you can investigate.

Upvotes: 1

Related Questions