Been working on a program recently and have a question about a problem I ran into. I've solved it, but don't know why it's happening:
for(int i = 0; i<10; i++)
{
Thread t = new Thread (() => {(does stuff, uses "i")});
}
Essentially I have 10 known processes I want to run on separate threads. In the thread, the value of the incrementor "i" is used to assign an object to a position in another array (I use locking). Now if I run it as is, I get an out of bounds error and when I debug with code breaks, I find that on that last loop i is equal to 10, when the last value should be 9. When this code isn't threaded, it works perfectly fine.
I decided to try and assign the incrementer to a local variable inside the thread:
for(int i = 0; i<10; i++)
{
Thread t = new Thread (() =>
{
localI=i;
(does stuff, uses "localI")
});
}
This had the same issue. I did more reading online and tried a different ordering of it:
for(int i = 0; i<10; i++)
{
localI=i;
Thread t = new Thread (() =>
{
(does stuff, uses "localI")
});
}
And this code works. I can't at all figure out why this works, but the second example didn't. Could anyone help me figure it out?
Thanks