by Administrator
17. April 2010 06:18
I can’t count the number of times I’ve had problems in Multi-Threaded C# / VB apps, nor can I count the number of times I’ve had to Google for the solution to this common problem. This week I finally found a generic method to handle the situation where you want to update UI from another thread.
public static class ThreadSafeInvokeExtension
{
public static void ThreadSafeInvoke<T>(this T @control, Action<T> toPerform) where T : ISynchronizeInvoke
{
if (@control.InvokeRequired)
@control.Invoke(toPerform, new object[] { @control });
else
toPerform(@control);
}
}
To use the extension method just do something like this:
textBox1.ThreadSafeInvoke(box => box.Text = value);
For more information on the Action<T> delegate used in this method check out the MSDN page here : http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
Another good use for the Action<T> delegate is on Steve Smith’s blog here : http://stevesmithblog.com/blog/eliminate-repetition-with-action-lt-t-gt/
b61ab570-0e8b-48bd-868b-c8f9c70ebd4e|0|.0
Tags: dotnet