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