Automating the InvokeRequired code pattern

后端 未结 9 1181
醉话见心
醉话见心 2020-11-21 23:57

I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where

private void DoGUISwitch() {
           


        
9条回答
  •  -上瘾入骨i
    2020-11-22 00:28

    You could write an extension method:

    public static void InvokeIfRequired(this Control c, Action action)
    {
        if(c.InvokeRequired)
        {
            c.Invoke(new Action(() => action(c)));
        }
        else
        {
            action(c);
        }
    }
    

    And use it like this:

    object1.InvokeIfRequired(c => { c.Visible = true; });
    

    EDIT: As Simpzon points out in the comments you could also change the signature to:

    public static void InvokeIfRequired(this T c, Action action) 
        where T : Control
    

提交回复
热议问题