# Improving GUI update call from a worker thread in winforms

I have a winforms app and I've been using the following approach to update controls on the main form from worker threads:

public static event EventHandler OnGamepadConnected;


Main app class has:

GamepadManager.OnGamepadConnected += OnGamepadConnected;
{
Invoke((Action)(() => { gamepadStatusLabel.Text = "Connected"; }));
}


That looks kinda bad, but without the Invoke thing I get a cross-thread operation exception because I can't update controls from worker threads (from where the call comes from).

Is there a way to reduce the number of parentheses used? Maybe there's a whole other, better way to do this?

Previously I've been using timers to check for every small thing like that, which ran on GUI thread (apparently?) and there was no trouble simply calling controlName.Text = "something"; without all the Invoke() stuff. But that means even more code and more processing cost due to constant checks.

You could create a helper method like the following:

void ChangeUI(Action action)
{
if (InvokeRequired)
{
Invoke(action);
}
else
{
action();
}
}


Now you can use it from any place where you need to modify the UI of that form and let the method check if it actually needs to call Invoke or simply execute the delegate.

ChangeUI(() => gamepadStatusLabel.Text = "Connected");

• This doesn't simplify the line with invoke call very much, and creates a new method. I don't think it's an improvement, really. May 20 '16 at 3:35
• @user1306322 I think it does simplify it by a lot. It certainly significantly decreases the number of parentheses. What else are you expecting? May 21 '16 at 15:21
• I'm expecting something I don't know, but perhaps that's too much in this case May 22 '16 at 0:04