【问题标题】:Extension Utility for invoking on a control's thread用于调用控件线程的扩展实用程序
【发布时间】:2012-05-09 17:14:44
【问题描述】:

我试图创建一个通用的实用程序,用于在主线程上调用。以下是我的想法 - 这样做有什么问题吗?检查 IsHandleCreated 和 IsDisposed 是多余的吗? Disposed时,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);
        }    
    }

提前致谢! 威廉

【问题讨论】:

  • 如果InvokeRequired 为真,调用将变为异步,而如果为假,则调用同步完成。

标签: c# user-interface multithreading


【解决方案1】:

我是自作聪明的回答,如有错误请见谅;

您不应该捕获异常,除非您期待它们并且知道在它们被抛出的情况下如何做出反应,如果不是这种情况最好让它们冒泡,直到它们到达您记录它的常见应用程序错误处理程序/显示一条消息或其他任何东西。

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

【讨论】:

    猜你喜欢
    • 2015-03-17
    • 2014-10-12
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多