有时遇到一种情况,.ShowDialog()不显示。也不报错。例如以下:
<span style="font-size:14px;"> private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(show);
thread.Start();
}
void show()
{
Control.CheckForIllegalCrossThreadCalls = false;
//this.Invoke(new Action(() =>
//{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{ }
//}));
}</span>
原因分析:这属于线程间操作的一种异常。界面呈现和新创建的thread分开在两个线程中。在thread线程中
不可以进行界面呈现,即显示.ShowDialog();
解决方法:1:加入參数this。
.ShowDialog(IWin32Window owner); //owner:表示将拥有模式对话框的*窗体
<span style="font-size:14px;"> private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(show);
thread.Start();
}
void show()
{
Control.CheckForIllegalCrossThreadCalls = false;
//this.Invoke(new Action(() =>
//{
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{ }
//}));
}</span>
2:使用Invoke
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(show);
thread.Start();
}
void show()
{
// Control.CheckForIllegalCrossThreadCalls = false;
this.Invoke(new Action(() =>
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{ }
}));
}