Does the inline code support the method [that wrote in it] in memory after completion?

Depending on what I know when I define a method in C #, the local variables in this method will be freed from memory after the execution of the block of this method is completed [when the GC wants],

but if I have a built-in callback in the method, will these local variables be also released from memory?

In the following example, the variable [x] will retain its value after the method has completed, and the message will display the value [x] without problems, although it is in the callback !!

    private void MyMethod()
    {
        int x = 1;
        System.Timers.Timer t = new System.Timers.Timer(1000);
        t.Elapsed += (sender, e) => MessageBox.Show((x++).ToString()); ;
        t.Start();
    }
+3
source share
1 answer

x , -. , x , MyMethod, ( , ).

(), # :

class $$MyMethod$$Closure { 
  public int x;
  void Function(object sender, EventArgs e) {
    MessageBox.Show((x++).ToString());
  }
}

private void MyMethod() {
    var $$closure = new $$MyMethod$$Closure();
    $$closure.x = 1; 
    System.Timers.Timer t = new System.Timers.Timer(1000); 
    t.Elapsed += $$closure.LambdaFunction; 
    t.Start(); 
}

, x ( ). , ( , x ), , .

, , - (, , , ).

+6

Source: https://habr.com/ru/post/1750755/


All Articles