Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confusion about ThreadPool in C#

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!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the documentation about lambdas

Lambdas can refer to outer variables. These are the variables that are in scope in the method that defines the lambda expression, or in scope in the type that contains the lambda expression. Variables that are captured in this manner are stored for use in the lambda expression even if the variables would otherwise go out of scope and be garbage collected. An outer variable must be definitely assigned before it can be consumed in a lambda expression.

Emphasis mine.

In effect the lambda expression will be rewritten by the compiler to a class, and any outer variable used in the expression will be added as fields in that class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading