当我使用 ShowDialog() 显示表单时,它会阻止 UI 和代码,但我只需要阻止 UI 而不是代码。
letturalog can3 = new letturalog();
(new System.Threading.Thread(() => {
can3.ShowDialog();
})).Start();
此模式不会阻塞代码和 UI。
所以我想知道你能不能做到这一点
最佳答案
如果不想屏蔽代码,那就调用.Show
换句话说,你想要:
can3.Show(this);
this.Enabled = false; //disable the form so the UI is blocked
//...do our stuff now that code is not blocked while the UI is blocked
//All done processing; unblock the UI:
this.Enabled = true;
事实上,这就是 ShowDialog
所做的全部工作:禁用表单,然后重新启用它。在伪代码中:
void ShowDialog(IWindowHandle Owner)
{
this.Show(Owner);
try
{
//Disable the owner form
EnableWindow(Owner, false);
repeat
{
Application.DoEvents();
}
until (this.DialogResult != DialogResult.None);
}
finally
{
//Re-enable the UI!
EnableWindow(owner, true);
}
}
你可以窃取所有这些概念,并用你想要的任何东西替换 guts:
void DoStuffWithTheThing()
{
can3.Show();
try
{
//Disable the owner form
this.Enabled = false;
//todo: Solve the P=NP conjecture
}
finally
{
//Re-enable the UI!
this.Enabled = true;
}
}
关于c# - ShowDialog 不阻塞执行代码但阻塞 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809104/