Automating the InvokeRequired code pattern

后端 未结 9 1195
醉话见心
醉话见心 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条回答
  •  悲&欢浪女
    2020-11-22 00:15

    Here's an improved/combined version of Lee's, Oliver's and Stephan's answers.

    public delegate void InvokeIfRequiredDelegate(T obj)
        where T : ISynchronizeInvoke;
    
    public static void InvokeIfRequired(this T obj, InvokeIfRequiredDelegate action)
        where T : ISynchronizeInvoke
    {
        if (obj.InvokeRequired)
        {
            obj.Invoke(action, new object[] { obj });
        }
        else
        {
            action(obj);
        }
    } 
    

    The template allows for flexible and cast-less code which is much more readable while the dedicated delegate provides efficiency.

    progressBar1.InvokeIfRequired(o => 
    {
        o.Style = ProgressBarStyle.Marquee;
        o.MarqueeAnimationSpeed = 40;
    });
    

提交回复
热议问题