Accessing UI from a Non-UI Thread

When attempting to manipulate UI elements from a thread different from the one that created the UI, an exception will be thrown.
To perform the operation from the UI thread, you need to define a delegate and re-Invoke itself.
For example, it looks like this:

delegate void setTextDelegate(string str);
private void setText(string str)
{
    if (this.InvokeRequired)// Re-invoke when called from another thread
    {
        setTextDelegate d = new setTextDelegate(setText);
        this.Invoke(d, str);
        return;
    }
    textBox1.Text = str;
}

Using Action (or Func) reduces the amount of code somewhat.

private void setText(string str)
{
    if (this.InvokeRequired)// Re-invoke when called from another thread
    {
        this.Invoke(new Action(() => setText(str)), null);
        return;
    }
    textBox1.Text = str;
}

However, if there are many functions that may be accessed from another thread, making the above modifications to each one is quite tedious. Ideally, we want to minimize changes to the original functions and reduce unnecessary branching.
In such cases, defining a function like the following execute within the same class, which receives a lambda expression as an Expression, simplifies the code.

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 function. Simply calls Execute.
{
    execute(() => _setText(str));
}
private void _setText(string str) // Add _ (underscore) to the original function name
{
    textBox1.Text = str;
}

Although you need to rename the original function, no changes to its internals are required.
If a return value is needed, you can do something like the following:

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 function. Simply calls Execute.
{
    return execute<string>(() => _getText());
}
private string _getText() // Add _ (underscore) to the original function name
{
    return textBox1.Text;
}

There is some overhead from compiling the Expression, so performance decreases slightly, but the benefit is reduced coding effort.