Wednesday 23 September 2009

Multi-threading with the help of Extension method

I love Extension methods!

For people who work with multi-threaded windows forms application, it's common to write code like this:

public void BindNewLoginList(object logins)
{
if (dgvLogins.InvokeRequired)
{
dgvLogins.BeginInvoke((System.Threading.ThreadStart)delegate()
{
BindNewLoginList(logins);
});
return;
}
dgvLogins.DataSource = logins;
}
But with the new extension feature of .Net Framework, I can create a method like this:
public static void ThreadSafeInvoke(this System.Windows.Forms.Control control, System.Threading.ThreadStart method)
{
if (control.InvokeRequired)
control.BeginInvoke(method);
else
method.DynamicInvoke();
}
Now, I simply call this method from any windows control, and it will take care of checking of the caller and invoke the method accordingly. How nice and neat it is!
public void BindNewLoginList(object logins)
{
dgvLogins.ThreadSafeInvoke(() => dgvLogins.DataSource = logins);
}