【发布时间】:2013-04-24 09:51:36
【问题描述】:
我有以下代码,我看到它以两种不同的方式编写。我只是好奇这两种方法中哪一种更好:
if (this.IsDisposed) return;
if (this.IsHandleCreated)
{
if (this.InvokeRequired)
{
this.Invoke(action);
}
else
{
action();
}
}
log.Error("Control handle was not created, therefore associated action was not executed.");
对比
if (this.InvokeRequired)
{
this.Invoke(action);
}
else
{
if (this.IsDisposed) return;
if (!this.IsHandleCreated)
{
log.Error("Control handle was not created, therefore associated action was not executed.");
return;
}
action();
}
我最关心的问题源于需要控件具有句柄的操作,而那些不是明确需要的。如果我要做这样的事情,它似乎通过确保控件在执行操作之前有句柄来解决我的问题。想法?
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
if (control.IsDisposed) return;
if (!control.IsHandleCreated)
{
// Force a handle to be created to prevent any issues.
log.Debug("Forcing a new handle to be created before invoking action.");
var handle = control.Handle;
}
action();
}
【问题讨论】:
-
第一个会阻塞直到动作完成,第二个不会。此外,使用 BeginInvoke 而不调用 EndInvoke 是不好的做法,因为可能的异常将被收集并且永远不会被释放。这是关于如何在没有 Begin / EndInvoke 的情况下在 winforms 中同步 gui 线程的链接:weblogs.asp.net/psteele/archive/2008/12/03/…
-
哎呀,那是 C&P 人工制品。它应该更像第一个块,这是我们的代码。第二个是我在这篇文章中找到的代码:aaronlerch.com/blog/2006/12/15/…
-
我最关心的是在未创建句柄时发生的异常,但我们尝试对这些 GUI 元素执行操作。通过将 control.Handle 分配给变量来强制创建句柄是不好的做法吗?
-
我不确定您将控制句柄分配给变量是什么意思。无论如何,如果您遇到此类问题,那么抑制错误将无法解决。如果您在未创建句柄时只是“返回”,那么您的程序几乎肯定会处于无效状态。
-
不确定手柄部分 tbh。我会选择 Control.CreateControl 因为你的方法看起来有点笨拙:) 见msdn.microsoft.com/en-us/library/…
标签: c# .net multithreading winforms