'Task List Throws "Collection was modified; enumeration operation may not execute."

Creating a list of Tasks to run parallel like this:

if (call.Item.PictureDetails != null)
{
    List<Task> lstTasks = new List<Task>();
    foreach (var url in call.Item.PictureDetails.PictureURL.Cast<string>().ToList())
    {
        var newTile = AddNewPicTile(url);
        lstTasks.Add(Task.Run(() => {
            UploadPicture(newTile);
        }));
    }
    // Run all pic upload tasks in parallel...
    await Task.WhenAll(lstTasks);
}

Execution throws "Collection was modified..." exception but I can't figure out why. I use similar code to this elsewhere in my app where I perform a while() loop that reads data from a database and it works fine. Like this...

        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                RadTileElement newTile = AddNewPicTile(rdr["PictureUrl"].ToString());   //...must create this var here otherwise we won't be able to access rdr from a background thread (it will be closed by then)
                
                lstTasks.Add(Task.Run(() => {
                    UploadPicture(newTile);
                }));
            }
        }
        rdr.Close();
    }
    conn.Close();
}

// Run all pic upload tasks in parallel...
await Task.WhenAll(lstTasks);

What is it about the string list that could cause it to yell at me like that?



Solution 1:[1]

Actually - problem was not related to List. Not even in the code posted. Thanks to Caius Jard who got me looking elsewhere for it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 William Madonna Jr.