需求:窗体中显示其他窗体,使用ShowDialog等待其他窗体耗时代码结束后,根据委托返回的结果,执行下方代码。
问题现象:也能等待耗时操作完成之后,执行判断 if (user1 == null),之后走的(b, u)=>{}里的代码
问题代码:
# 主窗体
Form form1 = new Form((b, u) =>
{
if (b)
{
if (u != null)
{
user1 = u;
}
}
else
{
MessageBox.Show("失败");
}
}, "确认人1");
form1.ShowDialog();
form1.Dispose();
if (user1 == null)
{
MessageBox.Show("获取用户1失败");
return;
}
# 其他窗体
Thread thread = new Thread(() =>
{
bytes=耗时操作
this.Invoke(() => { this.Close(); });
action1(bytes, s);
});
thread.IsBackground = true;
thread.Start();
原因:
先执行了Close();执行结束了ShowDialog,程序继续往下走。之后又执行了(b, u)=>{}
修改:
Thread thread = new Thread(() =>
{
bytes=耗时操作
action1(bytes, s);
this.Invoke(() => { this.Close(); });
});
thread.IsBackground = true;
thread.Start();