Accessing UI from a Non-UI Thread

Accessing UI controls from a thread other than the one that created them will throw an exception. To perform UI operations from the UI thread, you need to define a delegate and re-invoke yourself. For example:

delegate void setTextDelegate(string str);
private void setText(string str)
{
    if (this.InvokeRequired) // Called from a different thread — re-invoke via Invoke
    {
        setTextDelegate d = new setTextDelegate(setText);
        this.Invoke(d, str);
        return;
    }
    textBox1.Text = str;
}

Using Action (or Func) reduces the amount of code:

private void setText(string str)
{
    if (this.InvokeRequired) // Called from a different thread — re-invoke via Invoke
    {
        this.Invoke(new Action(() => setText(str)), null);
        return;
    }
    textBox1.Text = str;
}

When there are many methods that may be accessed from other threads, applying the above pattern to all of them becomes tedious. Ideally, we want to minimise changes to the original functions and reduce extra conditional branches. In such cases, defining the following execute helper method in the same class — which receives a lambda via an Expression — keeps the code clean and simple.

private void execute(Expression<Action> expression)
{
    if (this.InvokeRequired)
        this.Invoke(expression.Compile(), null);
    else
        expression.Compile().DynamicInvoke(null);
}
private void setText(string str) // New wrapper — just calls execute
{
    execute(() => _setText(str));
}
private void _setText(string str) // Original method renamed with _ prefix
{
    textBox1.Text = str;
}

The original method needs to be renamed, but its body requires no changes at all. When a return value is needed, the approach looks like this:

private Type execute<Type>(Expression<Func<Type>> expression)
{
    if (this.InvokeRequired)
        return this.Invoke(expression.Compile(), null);
    else
        return expression.Compile().DynamicInvoke(null);
}
private string getText() // New wrapper — just calls execute
{
    return execute<string>(() => _getText());
}
private string _getText() // Original method renamed with _ prefix
{
    return textBox1.Text;
}

There is a slight performance cost due to compiling the Expression, but the benefit is a significant reduction in boilerplate code.