我有以下代码,并且我已经看到它以两种不同的方式编写。我只是好奇这两种方法中哪一种更好:
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();
}