Collection was modified; enumeration operation may not execute
What's likely happening is that SignalData
is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing
foreach(Subscriber s in subscribers.Values)
To
foreach(Subscriber s in subscribers.Values.ToList())
If I'm right, the problem will disappear.
Calling subscribers.Values.ToList()
copies the values of subscribers.Values
to a separate list at the start of the foreach
. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.
C# - Collection was modified; enumeration operation may not execute
Obviuosly, your do something
code is trying to modify the collection.
It's generally a bad idea to modify the collection while iterating on it.
What you can do:
Copy collection to another.
foreach(Person j in lp.ToArray())
or
foreach(Person j in new List<Person>(lp))
Use temporary collection of modified items.
List<Person> itemsToDoSomething = new List<Person>();
foreach(Person j in lp)
itemsToDoSomething.Add(j);Then apply the desired action. For instance, remove items from collection:
lp.RemoveAll(item => itemsToDoSomething.Contains(item));
Unexpected 'Collection was modified; enumeration operation may not execute.' exception for List enumeration, despite List not being modified
The confusion you have stems from this assumption:
So I figured if I made a copy list
List<Vector2> originalAreaCopy = original.area;
This does not in fact make a copy of the list, it makes a copy of the reference to it. Reference type variables only store the reference to the object so in this case, you now have two variables both referencing the same object, the list, original.area
and originalAreaCopy
.
So when you later remove an object from the list, through originalAreaCopy
, it's still the exact same list you're iterating over, through original.area
. However, you still only have one list object.
In order to make a copy of the list and not just the reference to it, the easiest is probably just to do this:
List<Vector2> originalAreaCopy = original.area.ToList();
This will construct a new list containing all the elements in original.area
, so now original.area
and originalAreaCopy
actually references two distinct list objects.
collection was modified enumeration operation might not execute
You cannot modify a collection in a foreach
. Try this as an alternative to apomene's answer (Pretty much does the same thing, except using the remove method of a list instead of indexes.
List<DataRow> toDelete = new List<DataRow>();
foreach(DataRow dr in dt.Rows){
if(dr["Degree"].ToString() == field){
toDelete.Add(dr);
}
}
foreach (DataRow dr in toDelete){
dt.Rows.Remove(dr);
}
This should solve your problem.
Getting Collection was modified; enumeration operation may not execute. exception
Getting Collection was modified; enumeration operation may not execute. exception
Reason: This exception occurs when the enumeration that you are looping through is modified in same thread or some other thread.
Now, in the code that you have provided there isnn't any such scenario. Which means that you might be calling this in a multi-threaded environment and collection is modified in some other thread.
Solution: Implement locking on your enumeration so that only one thread gets access at a time. Something like this should do it.
private static Object thisLock = new Object();
public static string GetValue(List<StateBag> stateBagList, string name)
{
string retValue = string.Empty;
if (stateBagList != null)
{
lock(thisLock)
{
foreach (StateBag stateBag in stateBagList)
{
if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
retValue = stateBag.Value;
}
}
}
}
return retValue;
}
Error in datarow,Collection was modified; enumeration operation might not execute
Try this :
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var tempRow = dataTable.Rows[i];
var temp = dataTable.Rows[i][0];
for (int j = 0; j < dataTable.Rows.Count; j++)
{
DataRow rows = dataTable.Rows[j];
if (temp == rows[0].ToString())
{
tempdatatable.Rows.Add(tempRow[0], tempRow[1]);
dataTable.Rows.Remove(rows); //Update happen here
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
Collection was modified; enumeration operation may not execute randomly popping up - HTTP?
Overview:
It seemed that once I sent multiple requests to my API, these requests was conflicting with each other trying to overwrite the headers. I even tried clearing the headers first and then add them but yet I still encountered the above issue. The issue also started to include the exception: An item with the same key has already been added. Key: System.Net.Http.Headers.HeaderDescriptor
.
Resolution:
To solve this I refactored my service to do the following:
//Setup request
var request = new HttpRequestMessage(HttpMethod.Post, sharePointEndpoint)
{
Content = strContent
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", model.SharePointToken);
request.Headers.Add("Accept", "application/json;odata=verbose");
request.Headers.Add("X-HTTP-Method", "POST");
request.Headers.Add("ContentLength", bodyModelJson.Length.ToString());
// Send request, grab response
var response = await _httpClient.SendAsync(request);
In my case, the headers would depend on what operation I wanted to conduct. I removed the part where I was adding the default headers for HTTPClient and instead, added them within the request being made. As you can see, I now also used SendAsync();
I also injected HTTPClient as singleton. I had to initiate using my Constructor then afterwards whenever I want to use HTTPClient.
MyService:
private readonly HttpClient _httpClient;
public MyService(HttpClient httpClient)
{
_httpClient = httpClient;
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
/// SERVICES
services.AddSingleton<HttpClient>();
}
Hopefully this helps other people experiencing this issue.
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
Move the loop over animalsToRemove
outside the foreach
loop over animals
:
var animalsToRemove = new List<Animal>();
foreach(var animal in animals) <--- Error point
{
if(info.AnimalId == animal.AnimalId)
{
animalsToRemove.Add(animal);
foreach (var observer in observers)
{
observer.OnNext(info);
}
}
}
foreach (var animalToRemove in animalsToRemove)
{
animals.Remove(animalToRemove);
}
animalsToRemove.Clear();
Related Topics
How to Handle Both a Single Item and an Array For the Same Property Using Json.Net
When Should I Use a Struct Rather Than a Class in C#
How to Copy the Contents of One Stream to Another
How to Escape a Double Quote in a Verbatim String Literal
How to Change Property Names When Serializing With Json.Net
Does Json.Net Cache Types' Serialization Information
How to Evaluate C# Code Dynamically
The Type or Namespace Name Could Not Be Found
Do Event Handlers Stop Garbage Collection from Occurring
Case Insensitive 'Contains(String)'
Webbrowser Control in a New Thread
How to Get the Application'S Path in a .Net Console Application
What Is the C# Using Block and Why Should I Use It
Evaluating String "3*(4+2)" Yield Int 18
Protect .Net Code from Reverse Engineering