我有以下代码,我见过两种不同的写法。我只是好奇哪一种写法更好:
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();
}