Closures in C# - initating a thread in a function call with a value type

前端 未结 3 606
天涯浪人
天涯浪人 2021-01-28 17:43

I have this code, which works as I wanted but I don\'t understand exactly why. Thinking about a stack in C, C++, I\'d guess that the p variable will be on the stack on each call

相关标签:
3条回答
  • 2021-01-28 17:52

    It's not about closures, here is no any value capturing.

    What happening here is that your p parameter is copied by value into the thread's function. Everytime you pass to a function a new value of p is copied to a function.

    0 讨论(0)
  • 2021-01-28 18:07

    Lambdas are just glorified anonymous delegates

    • Rick Strahl (http://www.west-wind.com/weblog/posts/2008/Apr/26/Variable-Scoping-in-Anonymous-Delegates-in-C)

    Rick's article describes how the compiler generates a class that handles the enumTest p value and delegate.

    Also good info at Where does anonymous function body variables saved ?

    Basically the compiler creates a new instance of the "closure class" with local variables that must be passed to lambda. This is why you output is correct.

    UPDATE

    In the case of:

    for (int i=0; i<10; i++) 
    {
        var t = new Thread(() => { Console.WriteLine(i); }); 
        t.Start(); 
    }
    

    The variable i is shared between the for and the lambda. Each thread is accessing the same i. And since the for loop tends to finsih before any thread runs, all you see is '10'.

    See http://msdn.microsoft.com/en-us/library/0yw3tz5k(v=vs.80).aspx

    0 讨论(0)
  • 2021-01-28 18:14

    How does the closure of the thread captures it and more over, captures the correct value every time?

    That is compiler magic. Simply because the p parameter is being used by the lambda the compiler treats it differently. p is not placed on the stack but on the heap. That is why it still exists after callme() has terminated.

    0 讨论(0)
提交回复
热议问题