I' studying about ThreadPool in C# recently. And I wrote a small function to test it. Just as the code shown below:
static void threadTest()
{
int totalCnt = 2;
ManualResetEvent manual = new ManualResetEvent(false);
for(int i = 0; i < 2; ++i)
{
int cur = i;
Console.WriteLine("Before thread:" + cur);
ThreadPool.QueueUserWorkItem((s) => {
Console.WriteLine("In thread:" + cur);
if (Interlocked.Decrement(ref totalCnt) == 0) manual.Set();
});
Console.WriteLine("End thread:" + cur);
}
manual.WaitOne();
}
The output of this code is:
Before thread:0
End thread:0
Before thread:1
End thread:1
Before thread:2
End thread:2
Before thread:3
End thread:3
In thread:0
In thread:3
In thread:2
In thread:1
"In thread:xx" is printed after all loops are over. But every thread needs a temporary variable "cur" to output this line. However,as far as I know, a temporary variable in one loop will be removed from stack after the loop is over. In this example, thread can still visit "cur" when its loop is over. Can anyone explain this to me. Thanks!!