Hi I am reading the threading in c # tutorial. One of the things he mentions is this:
"The CLR assigns each thread its own memory stack, so local variables are stored separately."
And here is this example:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { for (int i = 0; i < 20; i++) { Thread t = new Thread(() => { Console.WriteLine(i); }); t.Start(); } Console.ReadLine(); } }
}
Conclusion: 1 2 2 4 6 8 10 10 10 10 12 12 14 15 17 18 18 20 20
So I understand what is going on here:
- The main thread starts the for loop.
- A new stream is created and defined in such a way that it gets the value "i" and print it on the console.
- The thread instance starts and the main thread continues to run.
Being an “i” integer, I assume that the new thread will have its own copy in the memory stack. Then print the value on the console. But, as the results show, its missing values jump from 10 to 12 or from 12 to 14. So, does the new thread get a link to i? But if "i" is an integer, then the new thread will not store the new value in the memory stack instead of what seems to be a reference to i.
Also, why are there duplicate values? His seal several times 2,10, 12, 18, 20.
Thanks.
source share