有時遇到一種情況,.ShowDialog()不顯示,也不報錯;如下:
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)
{ }
//}));
}
原因分析:這屬於線程間操作的一種異常。界面呈現和新創建的thread分開在兩個線程中。在thread線程中
不能夠進行界面呈現,即顯示.ShowDialog();
解決方法:1:添加參數this。
.ShowDialog(IWin32Window owner); //owner:表示將擁有模式對話框的頂級窗口
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)
{ }
//}));
}
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)
{ }
}));
}