Threading is not a magic bullet, it has to be planned and considered carefully - particularly when you are starting a bunch of them in a loop - because the parameters aren't actually converted to values until the thread is ready to go.
If I replace your code with this:
using System;
using System.Threading;
public class Program
{
public static void Main()
{
int numofrecords = 0;
for (int i = 0; i < 7; i++)
{
Thread thread = new Thread(() => Console.WriteLine("Thread {0}, {1}",i, numofrecords));
thread.Start();
numofrecords= numofrecords + 100000;
Console.WriteLine("{0} : {1}", i, numofrecords);
}
Thread.Sleep(2000);
}
}
The output you expect is this:
0 : 000000
Thread 0, 100000
1 : 100000
Thread 1, 200000
2 : 200000
Thread 2, 300000
3 : 300000
Thread 3, 400000
4 : 400000
Thread 4, 500000
5 : 500000
Thread 5, 600000
6 : 600000
Thread 6, 700000
The output I get is probably not what you expected:
0 : 100000
Thread 1, 100000
Thread 1, 100000
1 : 200000
2 : 300000
Thread 3, 300000
3 : 400000
Thread 4, 400000
4 : 500000
Thread 5, 500000
5 : 600000
Thread 6, 600000
6 : 700000
Thread 7, 700000
The first thread didn't get the values you expected because there is no locking, no thread safety at all - and the execution order is non-deterministic.
Meaning that if I run it again, I get different results:
0 : 100000
Thread 1, 100000
1 : 200000
Thread 2, 200000
2 : 300000
Thread 3, 300000
3 : 400000
Thread 4, 400000
4 : 500000
Thread 5, 500000
5 : 600000
Thread 6, 600000
6 : 700000
Thread 7, 700000
Which is better, but still not what you expected because the "i == 0" thread number never appears - it has already changed by the time the value of i has been taken and passed to the thread.
Try using Parallel.For instead, and multiply i by the block size instead of using two separate counters:
Parallel.For Method (System.Threading.Tasks) | Microsoft Learn[
^]