In C #, foreach should not be used in multithreading.

Source: Internet
Author: User

 

Recently, I encountered a problem where every element of an array needs to be operated on the thread, using the followingCode:

Private void foreachthread (INT [] ARR)
{
Foreach (int A in ARR)
{
New thread (delegate () {console. writeline ("Fe:" + a) ;}). Start ();
}
}

Some of the results are not output, but some are output repeatedly.

The code is changed to the following:

Private void forthread (INT [] ARR)
{
For (INT I = 0, Len = arr. length; I <Len; I ++)
{
Int A = arr [I];
New thread (delegate () {console. writeline (a) ;}). Start ();
}
}


Achieved the expected goal.

I didn't check the specific implementation method of foreach, but I am sorry here. If multithreading is required, try to avoid using foreach. foreach may not be thread-safe.
It is unknown whether for is thread-safe, but in the example, it should be thread-safe.

I don't know how to check whether the code is thread-safe. If you know something, please tell me. Thank you.

Related Article

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.