DCSIMG
Control.Invoke in C# 3.0 - part 2 - Ido Samuelson's blog

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;

                             });

}

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

Comments

# C# 3.0 saves my life as GUI developer « THE INSANE JAVA

Pingback from  C# 3.0 saves my life as GUI developer « THE INSANE JAVA

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: