C# : this.Invoke((MethodInvoker)delegate
Asked Answered
U

1

10

can somebody explain me the following code please :

                this.Invoke((MethodInvoker)delegate
                {
                    lblNCK.Text = cncType;
                });

Here is where it comes from :

        string cncType;

        if (objDMainCncData != null)
        {
            int rc = objDMainCncData.Init(objDGroupManager.Handle);

            if (rc == 0)
            {
                cncType = objDMainCncData.GetCncIdentifier();

                if (cncType != string.Empty)
                {
                    if (cncType.ToUpper().IndexOf("+") != -1)
                        _bFXplus = true;

                    this.Invoke((MethodInvoker)delegate
                    {
                        lblNCK.Text = cncType;
                    });
                }
            }
            else
            {
                DisplayMessage("objDMainCncData.Init() failed ! error : " + rc.ToString());
            }
        }
    }

I don't get the use of "this.Invoke((MethodInvoker)delegate".

Thank you by advance.

Peter.

Ultrasonics answered 7/4, 2016 at 9:9 Comment(0)
B
26

Strange that no one has answered this.

Lets take it in pieces:

this.Invoke: This is a synchronization mechanism, contained in all controls. All graphic/GUI updates, must only be executed from the GUI thread. (This is most likely the main thread.) So if you have other threads (eg. worker threads, async functions etc.) that will result in GUI updates, you need to use the Invoke. Otherwise the program will blow up.

delegate{ ... }: This is a anonymous function. You can think of it as "creating a function on the fly". (Instead of finding a space in the code, create function name, arguments etc.)

(MethodInvoker): The MethodInvoker is just the name of the delegate, that Invoke is expecting. Eg. Invoke expects to be given a function, with the same signature as the "MethodInvoker" function.

What happens, is that Invoke is given a function pointer. It wakes up the GUI thread through a mutex and tells it to executes the function (through the function pointer). The parent thread then waits for the GUI thread to finish the execution. And it's done.

Beverlybevers answered 15/3, 2017 at 8:34 Comment(1)
Additional: Represents a delegate that can execute any method in managed code that is declared void and takes no parameters. learn.microsoft.com/en-us/dotnet/api/…Honshu

© 2022 - 2024 — McMap. All rights reserved.