0

I'm getting tired of trying to figure out when and where an invoke is required. Rewriting this code over and over inline is tedious. I have created the method below to help solve this issue:

public void RunInvoked(object sender, Action method)
{
    Control This = sender as Control;

    if (This.InvokeRequired)
    {
        if (!This.IsHandleCreated) return;

        This.Invoke((MethodInvoker)delegate ()
        {
            method();
        });
    }
    else
    {
        method();
    }
}

(example method) And I call it as such :

private void EnableButton(bool enable)
{
    RunInvoked(this, () =>
    {
        if (enable)
        {
            this.buttonSet.Enabled = true;
            this.buttonSet.ForeColor = Color.Black;
            this.buttonSet.BackColor = Color.LightBlue;
        }
        else
        {
            this.buttonSet.Enabled = false;
            this.buttonSet.ForeColor = Color.Gray;
            this.buttonSet.BackColor = SystemColors.ButtonFace;
        }

        this.buttonSet.Update();
    });
}

I just want to make sure that this is sound logic and that it is not overlooking some glaring issues that I am unaware of before I start to implement this throughout my code. Also any help on making it even more generic would be appreciated if you feel so inclined. Thank you!

Lee Toffolo
  • 134
  • 1
  • 1
  • 10
  • The Invoke is needed to prevent Cross-Threading Exceptions. The Button Event is a separate process for the main thread and since you are writing to an object in another process you need the Invoke. – jdweng Feb 05 '19 at 14:57
  • @marsze, you may be right, that looks a lot like what I'm trying to do, and its not too far off from what I wrote, so that's probably a good indication that i'm headed in the correct direction. Any thoughts on the This.IsHandleCreated part? That seems to be the only logic that really differs. – Lee Toffolo Feb 05 '19 at 15:00

0 Answers0