I’ve just started programming in C#, and I’ve stumbled upon a small problem – lock doesn’t seem to work and I get a “Collection was modified after the enumerator was instantiated.” exception.
My code basically works like this:
private static object myLock = new object();
private Stack<MyObject> myObjects;
....
// Method that throws an exception
public void Update()
{
lock(myLock)
{
foreach (MyObject ob in myObjects)
{
ob.Update(); // has a foreach loop of it's own
}
}
}
// Method invoked by a click event
public void InvokedMethod()
{
lock(myLock)
{
myObjects.Push(new MyObject());
}
}
What am I doing wrong?
Thank you !
This is most likely to do with the code that you haven’t included inside the foreach block – what are you doing in the code you’ve missed out? If you’re modifying the screens collection (add or remove), this will cause the exception you have seen.