【问题标题】:How can I avoid Thread.Sleep when using the WPF Automation Framework?使用 WPF 自动化框架时如何避免 Thread.Sleep?
【发布时间】:2011-05-05 14:07:27
【问题描述】:

我正在尝试使用 WPF UI 自动化工作而不使用虚假的 thread.sleep 语句。我想做的是有一个函数 GetElementById 不断轮询,直到控件可用(或发生超时)。问题是它似乎缓存了我的父元素的子控件。是否可以刷新儿童?或者有人有其他方法吗?

public AutomationElement GetElementById(string id, int timeout)
{
    if (timeout <= 1000) throw new ArgumentException("Timeout must be greater than 1000", "timeout");

    AutomationElement element = null;

    int timer = 0;
    const int delay = 100;

    do
    {       
        element = MainWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, id));                
        Thread.Sleep(delay);
        timer += delay;
    } while (element == null && timer < timeout);

    if (element == null) throw new InvalidOperationException("Unable to find element with id: " + id);

    return element;
}

【问题讨论】:

  • 一些进一步的信息。我正在尝试获取特定选项卡上存在的元素。如果我在选项卡的 .select 之后进行线程睡眠,那么它可以工作。但是,如果我将线程睡眠作为方法的一部分,那么它就不起作用了。

标签: wpf automation ui-automation


【解决方案1】:

System.Windows.Forms.Application 命名空间中可用的 DoEvents 函数用于使 UI 能够在长时间运行的进程发生时进行更新。它不是 WPF 命名空间的成员。您可以通过像 article 那样自己实现它或导入 System.Windows.Forms 命名空间并调用 Application.DoEvents 来使用类似的东西。这将允许您在进行轮询时继续进行其他处理。这是一个需要谨慎使用的功能。

【讨论】:

  • 不幸的是,这并不能解决我的问题。还有其他想法吗?
【解决方案2】:

如果有比明智地使用 Thread.Sleep 更好的方法,我还没有找到。

UIAutomation 确实提供了Events,我想您可以(以您的情况为例)侦听选择 TabItem 时发生的事件,然后才能继续按 Id 查找项目。但我怀疑这种模式会严重破坏代码的整体可读性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    相关资源
    最近更新 更多