用于在控件的线程上调用的扩展实用工具

本文关键字:调用 扩展 实用工具 线程 控件 用于 | 更新日期: 2023-09-27 18:33:35

我试图创建一个一刀切的实用程序来调用主线程。 以下是我想出的 - 这样做有什么问题吗? 检查 IsHandleCreated 和 IsDispose 是否冗余? 当它被释放时,IsHandleCreated 是否会设置为 false?(因为这是布尔值的默认值)

    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/未初始化,则返回意味着您将隐藏一个可能的错误,为什么要这样做?我非常希望调用失败而不是不做任何事情就返回,如果您想防止出现 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();
}