Welcome to CSharp Labs

Using Lambda Expressions in Control Invoke Calls

Wednesday, June 5, 2013

The Control class implements ISynchronizeInvoke which provides a way to execute delegates on the thread that the control's handle was created on. The methods BeginInvoke, EndInvoke, Invoke use a System.Delegate parameter type which prevents using an lambda expression:

Since the C# compiler cannot determine which type of delegate to create when calling a method without an explicit delegate type, I have created extension methods that enable lambda expressions or anonymous method calls to ISynchronizeInvoke method implementations.

How it Works

The ISynchronizeInvokeExtensions extension class defines several invoking methods with Action and Func<T> delegate parameter types which enables the use of lambda expressions or anonymous methods.

Using

All ISynchronizeInvoke invoking methods are extended to accept Action and Func<T> delegate types where appropriate. In a class that implements ISynchronizeInvoke (System.Windows.Forms.Form), Invoke and BeginInvoke methods are extended to accept Action and Func<T> parameter types:

            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() =>
            {
                //executed the delegate asynchronously
                IAsyncResult result = this.BeginInvoke(() =>
                {
                    //Updates Text property
                    this.Text = "Text property updated from BeginInvoke.";
                });

                //completes asynchronous operation
                this.EndInvoke(result);

                //executes the function asynchronously
                result = this.BeginInvoke(() =>
                {
                    //accesses Text property
                    return this.Text;
                });

                //gets the return value of the function
                string text = (string)this.EndInvoke(result);

                Console.WriteLine(text); //Text property updated from BeginInvoke.

                //executes the delegate and waits until completed
                this.Invoke(() =>
                {
                    //updates Text property
                    this.Text = "Text property updated from Invoke.";
                });

                //executes the function and waits until completed and returns a value
                text = this.Invoke(() =>
                {
                    //accesses Text property
                    return this.Text;
                });

                Console.WriteLine(text); //Text property updated from Invoke.
            });

            t.Start();

Download ISynchronizeInvokeExtensions Extension Class

Comments