我遇到
Windows窗体应用程序的问题.
private delegate void DisplayDialogCallback(); public void DisplayDialog() { if (this.Invokerequired) { this.Invoke(new DisplayDialogCallback(DisplayDialog)); } else { this.ShowDialog(); } }
现在,每次运行它,都会抛出一个InvalidOperationException行this.ShowDialog();:
“跨线程操作无效:控制’SampleForm’从一个线程访问,除了它创建的线程.
这段代码怎么了?是不是有效的方式进行跨线程通话? ShowDialog()有什么特别之处吗?
解决方法
尝试这个:
private delegate void DisplayDialogCallback(); public void DisplayDialog() { if (this.Invokerequired) { this.Invoke(new DisplayDialogCallback(DisplayDialog)); } else { if (this.Handle != (IntPtr)0) // you can also use: this.IsHandleCreated { this.ShowDialog(); if (this.CanFocus) { this.Focus(); } } else { // Handle the error } } }
请注意Invokerequired返回
true if the control’s Handle was
created on a different thread than the
calling thread (indicating that you
must make calls to the control through
an invoke method); otherwise,false.
因此,如果控件尚未创建,返回值将为false!