First, this is not answered by this SO post, as that describes simple/basic object reference problems. What I'm experiencing is related to multithreaded async processing, which the other post doesn't solve.
I have a multithreaded .NET winforms app and I'm doing this:
if ( paramList != null ) {
lock ( paramList ) {
foreach ( DictionaryEntry param in paramList ) {
command.Parameters.AddWithValue(param.Key.ToString(), param.Value);
}
}
}
paramList
is an OrderedDictionary
.
I sporadically get this error on the foreach
line:
Object reference not set to an instance of an object.
As you can see, param.Key
is null and param.Value
is null. But this makes no sense because there are no nulls in paramList
, as you can see here:
In the screenshot you can see only index 2, but I examined index 0 and 1 also, same thing, valid data, no nulls.
I'm not experienced with multithreaded apps, but I put that block in a lock()
due to responses in this SO post. Before putting in the lock()
I was sporadically getting the error Collection was modified; enumeration operation may not execute.
After putting in the lock, that error went away, but now I'm getting the object reference as shown above.
What can I do to solve this?
EDIT
Taking the advice of a few posters, I did this:
private static object syncLock = new object();
and then down in the usage:
lock ( syncLock ) {
if ( paramList != null ) {
foreach ( DictionaryEntry param in paramList ) {
command.Parameters.AddWithValue(param.Key.ToString(), param.Value);
}
}
}
That seems to have solved the object reference error (thanks everyone), but now I sporadically get:
Collection was modified; enumeration operation may not execute.
Because I got a completely different error after trying this new approach, I created a new SO question. I'm not sure if that was the right thing to do because now it seems these problems are related and I'm just seeing different symptoms of the same core problem.
Still looking for a solution if anyone has ideas.