Welcome to DevAuthority.Com Sign in | Join | Help

Control.Invoke in C# 3.0 - part 2

After part 1 we can now make the code even more readable by creating Extension Method to System.Windows.Forms.Control

public static class ControlExtentions

{

    public delegate void InvokeHandler();

 

    public static bool SafeInvoke(this Control control, InvokeHandler handler)

    {

        if (control.InvokeRequired)

        {

            control.Invoke(handler);

            return false;

        }

 

        return true;

    }

}

Using it now will look like this:

public void UpdateStatus(string status)

{

    if (transfer.SafeInvoke(() => UpdateStatus(status)))

    {

        transfer.lblStatus.Text = status;

    }

}

The result code has some code that is redundant (the if statement). A small fix and we have this code :

public void UpdateStatus(string status)

{

    transfer.SafeInvoke(() =>

                             {

                                 transfer.lblStatus.Text = status;

                             });

}



Cross-post from http://blogs.microsoft.co.il/blogs/samuelson

Published Saturday, June 16, 2007 11:27 AM by Samuelson

Comments

# Windows Forms: A cool use for extension methods and LINQ expressions. « notgartner

Anonymous comments are disabled