次のコードがあり、2 つの異なる方法で記述されているのを見てきました。私は、2つの方法のどちらがより良い方法であるかに興味があります:
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();
}