Invoke Required when updating UI via another thread.

As you know, creating a Thread in the UI using System.Threading object (or any other thread object that is not UI related) does not allow that thread to access directly the UI objects (Eg: accessing a label “Text” property is not allowed).

The well know work around is to “Invoke the action in the UI” via delegate :

if (ctrl.InvokeRequired)
{
     ctrl.Invoke(....);
}

Another workaround is to use extension methods to add an “easy” way to invoke the UI logic.

using System;
using System.Windows.Forms;

public static partial class Extensions
{
    public static void InvokeIfRequired(this Control c, Action<Control> action)
    {
        if (c.InvokeRequired)
            c.Invoke(new Action(() => action(c)));
        else
            action(c);
    }
}

and then with

Label label1 = new Label();

call this method this way from the thread:

label1.InvokeIfRequired(c =>
{
    label1.Text = "Label updated via Threading object";
}
);

See also :
Extension Methods @ MSDN
Control.InvokeRequired Property @ MSDN


Leave a Reply