Automating the InvokeRequired code pattern

后端 未结 9 1188
醉话见心
醉话见心 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:18

    Usage:

    control.InvokeIfRequired(c => c.Visible = false);
    
    return control.InvokeIfRequired(c => {
        c.Visible = value
    
        return c.Visible;
    });
    

    Code:

    using System;
    using System.ComponentModel;
    
    namespace Extensions
    {
        public static class SynchronizeInvokeExtensions
        {
            public static void InvokeIfRequired(this T obj, Action action)
                where T : ISynchronizeInvoke
            {
                if (obj.InvokeRequired)
                {
                    obj.Invoke(action, new object[] { obj });
                }
                else
                {
                    action(obj);
                }
            }
    
            public static TOut InvokeIfRequired(this TIn obj, Func func) 
                where TIn : ISynchronizeInvoke
            {
                return obj.InvokeRequired
                    ? (TOut)obj.Invoke(func, new object[] { obj })
                    : func(obj);
            }
        }
    }
    

提交回复
热议问题