Note on using foreach in dictionary

Source: Internet
Author: User
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 ++ )
{
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.