Monday 29 June 2009

Generic InvokeRequired pattern - (C# Multi-Threading)

Tody I read article on InokeRequired patterns posted in code project ( Read Full Article )

I have wrote more generic version of the same ( Less code !!!!! ...clear & crisp...)

public static class ControlExtension
{
public static void UpdateControl(this Control control, MethodInvoker code)
{
if (control.InvokeRequired) {
control.Invoke(code);
}
else{
code.Invoke();
}
}

using 'Control' type param in Extension mentod give us an advantage to call UpdateControl on any control.

for eg:- In the below example I have called 'UpdateControl' extension method on textbox control.

private void btnUpdate_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart( () => txtInfo.UpdateControl(Display) ) );
th.Start();
}

private void Display()
{
txtInfo.Text += "Updated";
}

No comments:

Post a Comment