Capturing a parameter using lambda

What code is generated by the C # compiler when I try to capture a function parameter?

partial class NewClass : Window
{
    public NewClass()
    {
        InitializeComponent();
        new Thread(Work).Start();
    }

    void Work()
    {
        Thread.Sleep(5000); // Simulate time-consuming task
        UpdateMessage("The answer");
    }

    void UpdateMessage(string message)
    {
        Action action = () => txtMessage.Text = message;
        Dispatcher.BeginInvoke(action);
    }
}

I know that lambdas can store variables in its lexical area after creating a new class - where the specified variables are stored as fields. Fields replace any original appearance of captured ones. But in this case, since the original value is not replaced, is the value created from scratch? What is the magic behind this?

+4
source share
2 answers

So what is happening here is that you are not actually closing txtMessage, technically. What you are doing is closing this.

, this. , this.

, .

, this : ( #, #.)

void UpdateMessage(NewClass this, string message)
{
    Action action = () => this.txtMessage.Text = message;
    Dispatcher.BeginInvoke(action);
}

:

class ClosureClass1
{
    public string message;
    public NewClass @this;
    public void AnonymousMethod1()
    {
        @this.txtMessage.Text = message;
    }
}

void UpdateMessage(NewClass this, string message)
{
    ClosureClass1 closure = new ClosureClass1();
    closure.@this = this;
    closure.message = message;
    Action action = closure.AnonymousMethod1;
    Dispatcher.BeginInvoke(action);
}
+4

NewClass < > c__DisplayClass1 , "message". , UpdateMessage, < > c__DisplayClass1 , UpdateMessage ( ). <UpdateMessage> b__0, ( ). 'this', MainWindow.

enter image description here

enter image description here

enter image description here

, !

+2

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


All Articles