Mare Infinitus
Mare Infinitus

Reputation: 8172

How can this lambda variable be null?

There is a list of items which is written to from another thread.

The items are deleted synchronously. I have the following lambda in the delete part

var deleteList = this.Items.Where(d => d.Id == guid).ToList();

Sometimes, I get a NullReferenceException for d.

How can I find out more on that?

More information on the context

When removing or adding, I have a simple lock lock(myLock) In the adding part, I already check if the item is null (if (item != null) )

Having a simple (d != null) in the where clause will not prevent the items from getting null in the first place. In my opinion the list should already be in a "proper state".

Upvotes: 0

Views: 474

Answers (2)

Paul Fleming
Paul Fleming

Reputation: 24526

Threading or not, a reference in a reference can always be null. If you are deleting items from the same list, you need to place a lock on the item (or collection) before you work on it.

Without multi threading:

var deleteList = this.Items.Where(d => d != null && d.Id == guid).ToList();

Lock the collection something like this (note that there a various ways to do this):

lock(this.Items)
{
    var deleteList = this.Items.Where(d => d != null && d.Id == guid).ToList();
}

Upvotes: 1

Kane
Kane

Reputation: 16802

Try adding a check to see if d is null

d => d != null && d.Id.Equals(guid)

Upvotes: 0

Related Questions