Reputation: 2720
I have a thread that loads data when a service is starting. I call a method in this thread that uses Parallel.Foreach to iterate a set of data. But the linq query that I have inside the parallel forerach, gets a objet reference not set to an instance error.
*The same logic works if I remove the Parallel.Foreach though or if I remove the thread. *Even locking the list doesnt help.**
loadingThread = new Thread(new ThreadStart(PreloadData));
loadingThread.IsBackground = true;
loadingThread.Start();
---------------------------------------
public static void PreloadData()
{
Parallel.ForEach(loadedIDs.Keys, indexDefId =>
{
List<FixingEvent> lst = null;
lock (loadedEvents)
{
lst = (from e in loadedEvents where e.DIVACode.Equals(indexDefId) select e).ToList();
}
---------------------------
}
I get an exception in the linq query inside - ' e is null and hence object reference error'.
Any help is appreciated.
Upvotes: 1
Views: 1165
Reputation: 1875
You should not lock the loadedEvents
object. According to msdn:
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
you do not need to lock the object you are accessing - you simply need an object to lock on.
Upvotes: 1
Reputation: 171178
I guess the list loadedEvents contains null elements. Maybe due to a race condition.
Upvotes: 0