Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于在控件线程上调用的扩展实用程序_C#_User Interface_Multithreading - Fatal编程技术网

C# 用于在控件线程上调用的扩展实用程序

C# 用于在控件线程上调用的扩展实用程序,c#,user-interface,multithreading,C#,User Interface,Multithreading,我试图创建一个一刀切的实用程序,用于在主线程上调用。下面是我的想法——这样做有什么问题吗?检查IsHandleCreated和IsDisposed是否冗余?当它被释放时,IsHandleCreated是否会设置为false?因为这是bool的默认值 public static void InvokeMain(this Control Source, Action Code) { try { if (Source == nul

我试图创建一个一刀切的实用程序,用于在主线程上调用。下面是我的想法——这样做有什么问题吗?检查IsHandleCreated和IsDisposed是否冗余?当它被释放时,IsHandleCreated是否会设置为false?因为这是bool的默认值

    public static void InvokeMain(this Control Source, Action Code)
    {
        try
        {
            if (Source == null || !Source.IsHandleCreated || Source.IsDisposed) { return; }
            if (Source.InvokeRequired)
            {
                Source.BeginInvoke(Code);
            }
            else
            {
                Code.Invoke();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }    
    }
提前感谢!
威廉

我的回答是发自肺腑的,如果有任何错误,请原谅

您不应该捕获异常,除非您期望它们,并且知道在抛出异常时如何反应,如果不是这样,最好让它们冒泡,直到它们到达一个常见的应用程序错误处理程序,您可以在其中记录/显示消息或其他内容

如果控件为null/未初始化,则返回意味着您将隐藏一个可能的bug,为什么要这样做?我非常希望调用失败,而不是什么都不做就返回,如果要防止出现NullPointer异常,那么如果控件为null,您应该自己作为ArgumentNullException引发一个异常

public static void Invoke(this Control control, Action action)
{
    if (control == null)
        throw new ArgumentNullException("control");

    if (control.InvokeRequired)
    {
        control.Invoke(action);
        return;
    }

    action();
}

public static T Invoke<T>(this Control control, Func<T> action)
{
    if (control == null)
        throw new ArgumentNullException("control");

    if (control.InvokeRequired)
        return (T)control.Invoke(action);

    return action();
}

唯一可能影响您的是,如果InvokeRequired为true,则调用将变为异步调用,而如果为false,则调用将同步完成。