Thread-Safe DotNet UI Updates

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/

Tags:

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Shaw Innes

I'm an independent software developer, security consultant and digital media expert.  I have worked on a variety of projects over the last 10+ years ranging from simple websites, through to complex network security audits, digital media projects, iPhone applications, mobile communications frameworks and more.  Currently I work mainly in C# .NET and Objective C for iPhone / iPad development.