Sunday, January 30, 2011

Async updates of Windows Forms controls

Derick Bailey published this nice extension method to simplify the invokation of  Windows Forms controls outside the UI thread.

public static class ControlExtensions
{
public static void Do<TControl>(this TControl control, Action<TControl> action)
where TControl: Control
{
if (control.InvokeRequired)
control.Invoke(action, control);
else
action(control);
}
}


It's a simple extension method that allows any UI control to update itself when called from an asynchronous method - whether it's running from a .BeginInvoke() call, a BackgroundWorker, a ThreadPool thread, or any other form of asynchronous call. Simple, clean and useful.



Thanks Derick!

No comments: