c# - ShowDialog 不阻塞执行代码但阻塞 UI

标签 c# .net winforms visual-studio

当我使用 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/

相关文章:

c# - 从列表 C# 中查找不同的元素

c# - 如何将二维数组传递给存储过程?

c# - 从 NTFS-MFT 引用号获取文件信息

c# - 为什么 List<T>.Sort 方法重新排序等于 IComparable<T> 元素?

c# - 升级程序集时,迁移独立存储中文件的最佳方式是什么?

asp.net - C++ 中的 System::IO::Directory::GetFiles

c# - 使用 Windows 用户帐户凭据登录

c# - 模型绑定(bind)从 2.2 更改为 3.0 Asp.Net Core

c# - 如何将列表计数绑定(bind)到标签

c# - 如何检查唯一键约束