Well, I am bit new to concept of threads. I am at my initial stages of experimenting with it. I wrote the following code to see how threads placed in a list would execute.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static object obj = new object();
static void Main(string[] args)
{
List<Thread> threadList = new List<Thread>();
for (int i = 0; i < 10; i++)
{
threadList.Add(new Thread(() => ExecuteThread($"{ i }")));
}
foreach (var thread in threadList)
{
thread.Start();
}
return;
}
public static void ExecuteThread(string name)
{
Console.WriteLine($"In thread {name}");
lock (obj)
{
Console.WriteLine($"Inside the lock of thread {name}.");
Console.WriteLine("Waiting for keypress....");
Console.ReadKey();
}
return;
}
}
}
And I received the following OUTPUT :
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
In thread 10
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
Inside the lock of thread 10.
Waiting for keypress....
-------
Why does it show "Inside the lock of thread 10." instead of "Inside the lock of thread i" ? What feature of threads am I not understanding with this output ?
(With 'i', I mean the value of the i specified in the loop.)
What I have tried:
I had tried finding the instant values each variable using the debugger, but that was not of much help here.