Search code examples
c#multithreadinganonymous-methods

C#, invoke anonymous method (Action<>) from background thread


This should be simple!

I want to create an anonymous Action<> delegate to perform a GUI update, which I will call from several other anonymous delegates (which will be run on separate threads).

    void Test() {

        Action<string> invokeDisplay = new Action<string>(delegate(string Element) {
            //Do a variety of things to my GUI depending on Element parameter
        });


        MethodInvoker opLong1 = new MethodInvoker(delegate() {

        //  Do long task

            this.Invoke(invokeDisplay("long1"));
        });

        MethodInvoker opLong2 = new MethodInvoker(delegate() {

        //  Do long task

            this.Invoke(invokeDisplay("long2"));
        });

        new Thread(new ThreadStart(opLong1)).Start();
        new Thread(new ThreadStart(opLong2)).Start();
    }

So whats the correct syntax for this line?

            this.Invoke(invokeDisplay("long1"));

Solution

  • The syntax would be:

    Invoke(action, "long1");
    

    The delegate is the first parameter, and the argument(s) you want to pass to it follow.