C# : this.Invoke((MethodInvoker)delegate

14,522

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.

Share:
14,522
Admin
Author by

Admin

Updated on July 28, 2022

Comments

  • Admin
    Admin over 1 year

    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.

  • Soner from The Ottoman Empire
    Soner from The Ottoman Empire almost 5 years
    Additional: Represents a delegate that can execute any method in managed code that is declared void and takes no parameters. docs.microsoft.com/en-us/dotnet/api/…