I have a problem with array of threads in C#. When I start threads if for loop and send in parameter some threads get same value.
Thread[] nit = new Thread[n];
for (int i = 0; i < n; i++)
{
nit[i] = new Thread(() => functionThread(i + 1)); //functionThread => thread
nit[i].IsBackground = true;
nit[i].Name = string.Format("Thread: {0}", i + 1);
nit[i].Start();
Thread.Sleep(500); //I have problem here
}
for (int i = 0; i < n; i++)
{
nit[i].Join();
}
If n = 4 the values in threads should be 1, 2, 3, 4. But if i remove "Thread.Sleep(500);" or i set value less than 500 the values become for example 2, 2, 3, 4.
How could I make this work without Thread.Sleep() and still have correct values in threads?
Thank you in advance.