When I tried to learn C# List<>
underlying principles, I get the following information from here:
List uses the default constructor to create an empty list. As elements are added to the list, the capacity of the list expands to accommodate 4 elements. If a fifth element is added, the list is resized to contain 8 elements. Include 16 if 8 isn't enough. In short, each time the capacity of the list is reset to 2 times the original size.
That is easy to understand, but if I create Thread
and add them to List<Thread>
, I notice that it will still run the original Thread. Here is the code:
static void Main(string[] args)
{
List<Thread> LT = new List<Thread>();
for (int i = 0; i < 4; i++)
{
int time = i;
LT.Add(new Thread(() => { Thread.Sleep(1000 * time); Console.WriteLine(time); }));
LT[i].Start();
}
for (int i = 4; i < 8; i++)
{
int time = i;
LT.Add(new Thread(() => { Thread.Sleep(1000 * time); Console.WriteLine(time); }));
LT[i].Start();
}
Console.ReadLine();
}
I opened the source code of List
, and I found Array.Copy(_items, 0, array, 0, _size);
, which means it will deep copy the array. In that case, I tried to use GC.Collect();
to force the program delete the original array. However, threads created before the expansion mechanism occurred would still run while not changing anything, here is the output:
0 1 2 3 4 5 6 7
I wondering how C# implement this function.