【问题标题】:ShowDialog without Blocking Execution Code but Block UIShowDialog 不阻塞执行代码但阻塞 UI
【发布时间】:2016-04-23 09:41:19
【问题描述】:

当我使用 ShowDialog() 显示表单时,它会阻止 UI 和代码,但我只需要阻止 UI 而不是代码。

letturalog can3 = new letturalog();
                    (new System.Threading.Thread(() => {
                        can3.ShowDialog();
                    })).Start();

此模式不会阻塞代码和用户界面。

所以我想知道你是否可以这样做

【问题讨论】:

  • 如果你不想阻塞的代码在其他线程中,你已经做了。显示对话框只会阻塞调用它的线程。
  • 是的,但我已经写了 34.000 行代码.. 1 个 showdialog 不可能全部更改...
  • ShowDialog() 的工作原理是禁用应用程序中的所有窗口,然后在循环中调用 DoEvents() 直到分配 DialogResult 属性,然后重新启用所有窗口。所以你得到相同的结果,减去“阻止代码”,使用 Show() 并禁用所有窗口。

标签: c# .net winforms visual-studio


【解决方案1】:

如果你不想屏蔽代码,那么你想调用.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);
   } 
}

你可以窃取所有这些概念,并用你想要的任何东西替换胆量:

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;
   } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2016-01-18
    • 2018-01-08
    • 2014-05-25
    相关资源
    最近更新 更多