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.