all I have searched this question, and I found so many answers to it was not difficult to find a solution for my question. BUT, I have strange experience and I don't know the reason that's why I ask people to give me some advice. Here are my codes:
void SetThread()
{
for (int i = 0; i < _intArrayLength; i++)
{
Console.Write(string.Format("SetThread->i: {0}\r\n", i));
_th[i] = new Thread(new ThreadStart(() => RunThread(i)));
_th[i].Start();
}
}
void RunThread(int num)
{
Console.Write(string.Format("RunThread->num: {0}\r\n", num));
}
Yes, they are ordinary thread codes. I expect all the thread array should be calling RunThread method 10 times. It should be like
SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
SetThread->i: 3
SetThread->i: 4
SetThread->i: 5
SetThread->i: 6
SetThread->i: 7
SetThread->i: 8
SetThread->i: 9
RunThread->num: 0
RunThread->num: 1
RunThread->num: 2
RunThread->num: 3
RunThread->num: 4
RunThread->num: 5
RunThread->num: 6
RunThread->num: 7
RunThread->num: 8
RunThread->num: 9
This is what I expect to be. The order is not important. But I get the result like below.
SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
The thread '<No Name>' (0x18e4) has exited with code 0 (0x0).
The thread '<No Name>' (0x11ac) has exited with code 0 (0x0).
The thread '<No Name>' (0x1190) has exited with code 0 (0x0).
The thread '<No Name>' (0x1708) has exited with code 0 (0x0).
The thread '<No Name>' (0xc94) has exited with code 0 (0x0).
The thread '<No Name>' (0xdac) has exited with code 0 (0x0).
The thread '<No Name>' (0x12d8) has exited with code 0 (0x0).
The thread '<No Name>' (0x1574) has exited with code 0 (0x0).
The thread '<No Name>' (0x1138) has exited with code 0 (0x0).
The thread '<No Name>' (0xef0) has exited with code 0 (0x0).
SetThread->i: 3
RunThread->num: 3
RunThread->num: 3
RunThread->num: 3
SetThread->i: 4
RunThread->num: 4
SetThread->i: 5
SetThread->i: 6
RunThread->num: 6
RunThread->num: 6
SetThread->i: 7
RunThread->num: 7
SetThread->i: 8
RunThread->num: 8
SetThread->i: 9
RunThread->num: 9
RunThread->num: 10
What I expect is that RunThread function should carry the argument(num) from 0 to 9. And I cannot figure out what that error message is. "The thread '' ~~ and so on. Could anyone give me some clue on this?
ithrough a closure. (Created by the lambda you pass toThreadStart.) They do not get a copy of the current value ofiwhen theThreadobject is created, but the value ofiwhenRunThreadis finally called, which happens later after you start the thread and it finishes initialising etc - the loop will have progressed at that point. As you see from your output, that's exactly what happens,RunThreadprints out the last value seen inSetThread.var ii = i;inside theforloop, and usingiiin the argument toThreadStart. That will make the lambdas close over different "instances" of the local variable. (The difference is that the loop counter's scope is outside the loop body, a local variable inside.) Unless I'm confusing things with Javascript.