Getting Collection was modified; enumeration operation may not execute. exception
c#
Solution
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;
}
Problem
Getting Collection was modified; enumeration operation may not execute. exception Code: ``` public static string GetValue(List<StateBag> stateBagList, string name) { string retValue = string.Empty; if (stateBagList != null) { foreach (StateBag stateBag in stateBagList) { if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) { retValue = stateBag.Value; } } } return retValue; } ``` getting this exception some time times not every time at this place. stacktrace: at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.List`1.Enumerator.MoveNextRare() at System.Collections.Generic.List`1.Enumerator.MoveNext() at Tavisca.TravelNxt.Shared.Entities.StateBag.GetValue(List`1 stateBagList, String name) @no one i have tried for following code but still getting exception code: ``` class StateBag { public string Name; public string Value; } class Program { static List<StateBag> _concurrent = new List<StateBag>(); static void Main() { var sw = new Stopwatch(); try { sw.Start(); Thread thread1 = new Thread(new ThreadStart(A)); Thread thread2 = new Thread(new ThreadStart(B)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); sw.Stop(); } catch (Exception ex) { } Console.WriteLine("Average: {0}", sw.ElapsedTicks); Console.ReadKey(); } 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; } static void A() { for (int i = 0; i < 5000; i++) { _concurrent.Add(new StateBag() { Name = "name" + i, Value = i.ToString() }); } } static void B() { for (int i = 0; i < 5000; i++) { var t = GetValue(_concurrent, "name" + i); } } } ```