【问题标题】:Pausing execution of method running on UI thread暂停在 UI 线程上运行的方法的执行
【发布时间】:2017-01-31 20:28:51
【问题描述】:

我有一个窗口,里面有一个浏览器控件。当有人关闭窗口时,我需要将浏览器控件导航到特定的 URL,并且只有在浏览器完成导航后才需要关闭窗口。

当窗口关闭时,OnBeforeWindowClose(Eventargs e) 方法被调用。

OnBeforeWindowClose(Eventargs e)
{

// As soon as the URL property is set the browser control navigates to the URL  

URL = "new URL";

//I need to wait till the browser is done navigating. Based on the NavigationFinished  property below

}

bool NavigationFinished {set; get;}

我不能使用Thread.Sleep,因为它会导致 UI 线程休眠。我想不出一种方法来暂停 OnBeforeClose 的执行,直到 NavigationFinised 变为真。不阻塞 UI 线程。

更新:将以下循环添加到 OnBeforeWindowClose 方法对我有用

do
        {
            var dateTime = DateTime.Now.AddSeconds(2);
            while (DateTime.Now < dateTime)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        } while (!NavigationFinished);

但我想知道是否有更好的方法来做到这一点,而不是在 .Net 4.0 中使用循环

【问题讨论】:

  • 您正在寻找await
  • 它在 .net 4.0 中不可用 :(
  • 在 NuGet 上安装 Microsoft.Bcl.Async
  • 我无法使用 Microsoft.Bcl.Async。但是将以下循环添加到 OnBeforeWindowClose 方法对我有用。有没有更好的方法来停止方法执行而不是循环。
  • 做 { var dateTime = DateTime.Now.AddSeconds(2);而(日期时间。现在

标签: c# .net wpf c#-4.0


【解决方案1】:

这在某种程度上是一种解决方法,但可以满足您的要求:

  • 监听窗口关闭事件。
  • 当 Windows_Closing 处理程序正在执行时,检查浏览器当前 URL:如果不是“新 URL”,则取消关闭事件(参见 https://msdn.microsoft.com/en-us/library/system.windows.window.closing(v=vs.110).aspx
  • 下一个钩子到 Webbrowser 上的 LoadCompleted,然后将浏览器 URL 设置为“新 URL”,当 LoadCompleted 处理程序命中时,再次调用 Windows.Close() 方法(当浏览器 url 具有再次执行 close 方法时已设置为“新 URL”)。

所以这里的想法是通过取消 - 做某事 - 然后以编程方式重新关闭来实现暂停。

【讨论】:

  • 关闭窗口实际上是从应用程序关闭中调用的。而且我无法调用应用程序关闭方法。即我无法以编程方式重新关闭:(我需要在中途暂停 onBeforeClose 方法并在浏览器导航后恢复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多