Recently Program Performs performance optimization and uses dictionary during the optimization process. In When the data in is written to the database, the following error occurs:
Collection was modified; enumeration operation may not execute.
Code Similar to this: Dictionary < Int , Int > _ Dictionary = New Dictionary < Int , In > ();
// Adding data operation omitted
Foreach (Keyvaluepair < Int , Int > Item In _ Dictionary)
{
}
When foreach is executed, other threads Add _ dictionary, which changes the data in _ dictionary and generates the preceding exception information.
So what will generate such exception information?
The actual code executed by foreach is:
Dictionary < Int , Int > . Enumerator = _ Dictionary. getenumerator ();
Try
{
While (Enumerator. movenext ())
{
}
}
Finally
{
Idisposable d = Enumerator As Idisposable;
If (D ! = Null ) D. Dispose ();
}
View dictionary using reflector . enumerator. movenext () Source Code , we will find the code at the beginning: If ( This . version ! = This . dictionary. version)
{< br> throwhelper. throwinvalidoperationexception (exceptionresource. invalidoperation_enumfailedversion);
}
The exception occurs here because the version of the dictionary is changed during the add operation. You can view the source code of insert (tkey, tvalue, bool add.
I think dictionary <tkey, tvalue> should provide a method to set whether to perform version check in movenext, because sometimes in foreach operations, it may not care whether the data in the dictionary is modified, I have encountered this situation. Due to this problem, foreach cannot be used, but only other methods can be used to traverse data in dictionary <tkey, tvalue>.
The method I use is:
Dictionary < Int , Int > _ Dictionary = New Dictionary < Int , In > ();
// Adding data operation omitted
Int [] Dataarray = New Int [_ Dictionary. Values. Count];
_ Dictionary. Values. copyto (evcarray, 0 )
For ( Int I = 0 ; I < Dataarray. length; I ++ )
{
}