简体   繁体   中英

Linq strange behavior

Statment:

(definitions != null && definitions.Where(key => key.asset_id != null &&
                                          key.asset_id == item).FirstOrDefault() != null

Throws:

collection was modified enumeration operation may not execute

How to fix this?

if (definitions != null 
    && definitions
         .Where(key => key.asset_id != null && key.asset_id == item)
         .FirstOrDefault() != null)
{
    CurrentDuration = definitions
                        .Where(key => key.asset_id != null && key.asset_id == item)
                        .FirstOrDefault().duration;
}

The problem is that somewhere in your code the definitions collection is modified. Mostly it's because of collection modification in another thread, but it could have some other reasons. You should find out the piece of code which is modifying collection somewhere else. You can protect the definitions variable using a lock wherever you're using definitions .

if (definitions != null)
{
    lock (definiitons)
    {
        var definition = definitions.FirstOrDefault(key => key.asset_id != null && key.asset_id == item);
        if (definition != null)
            CurrentDuration = definition.duration;
    }
}

and put lock everywhere you're modifying the definitions or its references, for example:

lock (definitions)
{
    definitions.Add(x);
}

or

lock (definitions)
{
    definitions.Remove(x);
}

or even

var otherRef = definitions
lock (otherRef )
{
    otherRef .Add(x);
}

I assume that "CurrentDuration" is a foreach loop variable counter.

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add ,remove or change items from the source collection to avoid unpredictable side effects. If you need to add, remove or change items from the source collection, use a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM