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

GamepadManager class has:

public static event EventHandler OnGamepadConnected;

Main app class has:

GamepadManager.OnGamepadConnected += OnGamepadConnected;
private void 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)

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");
  • \$\begingroup\$ 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. \$\endgroup\$ May 20 '16 at 3:35
  • 2
    \$\begingroup\$ @user1306322 I think it does simplify it by a lot. It certainly significantly decreases the number of parentheses. What else are you expecting? \$\endgroup\$
    – svick
    May 21 '16 at 15:21
  • \$\begingroup\$ I'm expecting something I don't know, but perhaps that's too much in this case \$\endgroup\$ May 22 '16 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.