CacheRequest Class

Definition

Определяет свойства и шаблоны, которые платформа автоматизации пользовательского интерфейса кэширует при получении элемента AutomationElement.Specifies properties and patterns that the UI Automation framework caches when an AutomationElement is obtained.

public ref class CacheRequest sealed
public sealed class CacheRequest
type CacheRequest = class
Public NotInheritable Class CacheRequest
Inheritance
CacheRequest

Examples

В следующем примере показано, как использовать Activate для кэширования шаблонов и свойств.The following example shows how to use Activate to cache patterns and properties.

/// <summary>
/// Caches and retrieves properties for a list item by using CacheRequest.Activate.
/// </summary>
/// <param name="elementList">Element from which to retrieve a child element.</param>
/// <remarks>
/// This code demonstrates various aspects of caching. It is not intended to be 
/// an example of a useful method.
/// </remarks>
private void CachePropertiesByActivate(AutomationElement elementList)
{
    AutomationElement elementListItem;

    // Set up the request.
    CacheRequest cacheRequest = new CacheRequest();
    cacheRequest.Add(AutomationElement.NameProperty);
    cacheRequest.Add(AutomationElement.IsEnabledProperty);
    cacheRequest.Add(SelectionItemPattern.Pattern);
    cacheRequest.Add(SelectionItemPattern.SelectionContainerProperty);

    // Obtain an element and cache the requested items.
    using (cacheRequest.Activate())
    {
        Condition cond = new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true);
        elementListItem = elementList.FindFirst(TreeScope.Children, cond);
    }
    // The CacheRequest is now inactive.

    // Retrieve the cached property and pattern.
    SelectionItemPattern pattern;
    String itemName;
    try
    {
        itemName = elementListItem.Cached.Name;
        pattern = elementListItem.GetCachedPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Object was not in cache.");
        return;
    }
    // Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
    object cachedPattern;
    if (true == elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, out cachedPattern))
    {
        pattern = cachedPattern as SelectionItemPattern;
    }

    // Specified pattern properties are also in the cache.
    AutomationElement parentList = pattern.Cached.SelectionContainer;

    // The following line will raise an exception, because the HelpText property was not cached.
    /*** String itemHelp = elementListItem.Cached.HelpText; ***/

    // Similarly, pattern properties that were not specified in the CacheRequest cannot be 
    // retrieved from the cache. This would raise an exception.
    /*** bool selected = pattern.Cached.IsSelected; ***/

    // This is still a valid call, even though the property is in the cache.
    // Of course, the cached value and the current value are not guaranteed to be the same.
    itemName = elementListItem.Current.Name;
}
''' <summary>
''' Caches and retrieves properties for a list item by using CacheRequest.Activate.
''' </summary>
''' <param name="elementList">Element from which to retrieve a child element.</param>
''' <remarks>
''' This code demonstrates various aspects of caching. It is not intended to be 
''' an example of a useful method.
''' </remarks>
Private Sub CachePropertiesByActivate(ByVal elementList As AutomationElement)

    ' Set up the request.
    Dim myCacheRequest As New CacheRequest()
    myCacheRequest.Add(AutomationElement.NameProperty)
    myCacheRequest.Add(AutomationElement.IsEnabledProperty)
    myCacheRequest.Add(SelectionItemPattern.Pattern)
    myCacheRequest.Add(SelectionItemPattern.SelectionContainerProperty)

    Dim elementListItem As AutomationElement

    ' Obtain an element and cache the requested items.
    Using myCacheRequest.Activate()
        Dim myCondition As New PropertyCondition( _
            AutomationElement.IsSelectionItemPatternAvailableProperty, True)
        elementListItem = elementList.FindFirst(TreeScope.Children, myCondition)
    End Using


    ' The CacheRequest is now inactive.
    ' Retrieve the cached property and pattern.
    Dim pattern As SelectionItemPattern
    Dim itemName As String
    Try
        itemName = elementListItem.Cached.Name
        pattern = DirectCast(elementListItem.GetCachedPattern(SelectionItemPattern.Pattern), _
            SelectionItemPattern)
    Catch ex As InvalidOperationException
        Console.WriteLine("Object was not in cache.")
        Return
    End Try
    ' Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
    Dim cachedPattern As Object = Nothing
    If True = elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, cachedPattern) Then
        pattern = DirectCast(cachedPattern, SelectionItemPattern)
    End If

    ' Specified pattern properties are also in the cache.
    Dim parentList As AutomationElement = pattern.Cached.SelectionContainer

    ' The following line will raise an exception, because the HelpText property was not cached.
    '** String itemHelp = elementListItem.Cached.HelpText; **

    ' Similarly, pattern properties that were not specified in the CacheRequest cannot be 
    ' retrieved from the cache. This would raise an exception.
    '** bool selected = pattern.Cached.IsSelected; **

    ' This is still a valid call, even though the property is in the cache.
    ' Of course, the cached value and the current value are not guaranteed to be the same.
    itemName = elementListItem.Current.Name
End Sub

В следующем примере показано, как использовать Push и Pop для кэширования шаблонов и свойств.The following example shows how to use Push and Pop to cache patterns and properties.

/// <summary>
/// Caches and retrieves properties for a list item by using CacheRequest.Push.
/// </summary>
/// <param name="autoElement">Element from which to retrieve a child element.</param>
/// <remarks>
/// This code demonstrates various aspects of caching. It is not intended to be 
/// an example of a useful method.
/// </remarks>
private void CachePropertiesByPush(AutomationElement elementList)
{
    // Set up the request.
    CacheRequest cacheRequest = new CacheRequest();

    // Do not get a full reference to the cached objects, only to their cached properties and patterns.
    cacheRequest.AutomationElementMode = AutomationElementMode.None;

    // Cache all elements, regardless of whether they are control or content elements.
    cacheRequest.TreeFilter = Automation.RawViewCondition;

    // Property and pattern to cache.
    cacheRequest.Add(AutomationElement.NameProperty);
    cacheRequest.Add(SelectionItemPattern.Pattern);

    // Activate the request.
    cacheRequest.Push();

    // Obtain an element and cache the requested items.
    Condition cond = new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true);
    AutomationElement elementListItem = elementList.FindFirst(TreeScope.Children, cond);

    // At this point, you could call another method that creates a CacheRequest and calls Push/Pop.
    // While that method was retrieving automation elements, the CacheRequest set in this method 
    // would not be active. 

    // Deactivate the request.
    cacheRequest.Pop();

    // Retrieve the cached property and pattern.
    String itemName = elementListItem.Cached.Name;
    SelectionItemPattern pattern = elementListItem.GetCachedPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;

    // The following is an alternative way of retrieving the Name property.
    itemName = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty) as String;

    // This is yet another way, which returns AutomationElement.NotSupported if the element does
    // not supply a value. If the second parameter is false, a default name is returned.
    object objName = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty, true);
    if (objName == AutomationElement.NotSupported)
    {
        itemName = "Unknown";
    }
    else
    {
        itemName = objName as String;
    }

    // The following call raises an exception, because only the cached properties are available, 
    //  as specified by cacheRequest.AutomationElementMode. If AutomationElementMode had its
    //  default value (Full), this call would be valid.
    /*** bool enabled = elementListItem.Current.IsEnabled; ***/
}
''' <summary>
''' Caches and retrieves properties for a list item by using CacheRequest.Push.
''' </summary>
''' <param name="elementList">Element from which to retrieve a child element.</param>
''' <remarks>
''' This code demonstrates various aspects of caching. It is not intended to be 
''' an example of a useful method.
''' </remarks>
Private Sub CachePropertiesByPush(ByVal elementList As AutomationElement)
    ' Set up the request.
    Dim cacheRequest As New CacheRequest()

    ' Do not get a full reference to the cached objects, only to their cached properties and patterns.
    cacheRequest.AutomationElementMode = AutomationElementMode.None

    ' Cache all elements, regardless of whether they are control or content elements.
    cacheRequest.TreeFilter = Automation.RawViewCondition

    ' Property and pattern to cache.
    cacheRequest.Add(AutomationElement.NameProperty)
    cacheRequest.Add(SelectionItemPattern.Pattern)

    ' Activate the request.
    cacheRequest.Push()

    ' Obtain an element and cache the requested items.
    Dim myCondition As New PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, _
        True)
    Dim elementListItem As AutomationElement = elementList.FindFirst(TreeScope.Children, myCondition)

    ' At this point, you could call another method that creates a CacheRequest and calls Push/Pop.
    ' While that method was retrieving automation elements, the CacheRequest set in this method 
    ' would not be active. 
    ' Deactivate the request.
    cacheRequest.Pop()

    ' Retrieve the cached property and pattern.
    Dim itemName As String = elementListItem.Cached.Name
    Dim pattern As SelectionItemPattern = _
        DirectCast(elementListItem.GetCachedPattern(SelectionItemPattern.Pattern), SelectionItemPattern)

    ' The following is an alternative way of retrieving the Name property.
    itemName = CStr(elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty))

    ' This is yet another way, which returns AutomationElement.NotSupported if the element does
    ' not supply a value. If the second parameter is false, a default name is returned.
    Dim objName As Object = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty, True)
    If objName Is AutomationElement.NotSupported Then
        itemName = "Unknown"
    Else
        itemName = CStr(objName)
    End If
    ' The following call raises an exception, because only the cached properties are available, 
    '  as specified by cacheRequest.AutomationElementMode. If AutomationElementMode had its
    '  default value (Full), this call would be valid.
    '** bool enabled = elementListItem.Current.IsEnabled; **

End Sub

Remarks

Получение свойств и шаблонов с помощью Автоматизация пользовательского интерфейсаUI Automation требует межпроцессных вызовов, которые могут замедлить производительность.Retrieving properties and patterns through Автоматизация пользовательского интерфейсаUI Automation requires cross-process calls that can slow down performance. Кэширование в пакетной операции значений, характерных для частных приложений и шаблонов, позволяет повысить производительность приложения.By caching values of proprieties and patterns in a batch operation, you can enhance the performance of your application.

Создайте новый запрос к кэшу, вызвав конструктор класса.Create a new cache request by calling the class constructor. Запрос заполняется повторными вызовами метода Add.The request is populated by repeated calls to the Add method.

Активным может быть только один CacheRequest.Only a single CacheRequest can be active. Существует два способа активации запроса.There are two ways to activate a request:

  • Вызовите Activate запроса.Call Activate on the request. Это помещает запрос в стек, и запрос извлекается при удалении объекта.This pushes the request onto the stack, and the request is popped when the object is disposed. Чтобы обеспечить реализацию даже при возникновении исключения, используйте возвращаемое значение из Activate в блоке using (Using в Visual Basic).To ensure disposal even if an exception is raised, use the return value from Activate within a using block (Using in Visual Basic).

  • Разместите запрос во внутреннем стеке, вызвав Push.Put the request onto the internal stack by calling Push. Активен только самый верхний запрос в стеке, и он должен быть следующим, удаленным из стека Pop.Only the topmost request on the stack is active, and it must be the next one removed from the stack by Pop. При извлечении запроса он деактивируется.Popping the request deactivates it.

Автоматизация пользовательского интерфейсаUI Automation элементы, полученные, пока запрос активен, будут иметь кэшированные значения для указанных свойств и шаблонов.elements obtained while the request is active will have cached values for the properties and patterns specified.

Constructors

CacheRequest()

Инициализирует новый экземпляр класса CacheRequest.Initializes a new instance of the CacheRequest class.

Properties

AutomationElementMode

Возвращает или задает значение, которое показывает, должны ли возвращаемые элементы содержать полные ссылки на базовый пользовательский интерфейсuser interface (UI) или только кэшированные данные.Gets or sets a value that specifies whether returned elements should contain full references to the underlying пользовательский интерфейсuser interface (UI), or only cached information.

Current

Возвращает запрос CacheRequest, который является активным в текущем потоке.Gets the CacheRequest that is active on the current thread.

TreeFilter

Возвращает или задает значение, определяющее представление дерева элементов Автоматизация пользовательского интерфейсаUI Automation, используемое при кэшировании.Gets or sets a value specifying the view of the Автоматизация пользовательского интерфейсаUI Automation element tree to use when caching.

TreeScope

Возвращает или задает значение, которое показывает, выполняется ли кэширование только для корня вложенного дерева или также для дочерних элементов и потомков.Gets or sets a value that specifies whether caching is done only for the root of the subtree, or also for its children or descendants.

Methods

Activate()

Определяет данный запрос CacheRequest как активную спецификацию для элементов, которые возвращаются, когда элемент AutomationElement запрашивается в том же потоке.Sets this CacheRequest as the active specification for the items that are returned when an AutomationElement is requested on the same thread.

Add(AutomationPattern)

Добавляет указанный идентификатор AutomationPattern к данному запросу CacheRequest.Adds the specified AutomationPattern identifier to this CacheRequest.

Add(AutomationProperty)

Добавляет указанный идентификатор AutomationProperty к данному запросу CacheRequest.Adds the specified AutomationProperty identifier to this CacheRequest.

Clone()

Создает копию данного объекта CacheRequest.Creates a copy of this CacheRequest.

Equals(Object)

Определяет, равен ли заданный объект текущему объекту.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Служит хэш-функцией по умолчанию.Serves as the default hash function.

(Inherited from Object)
GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Inherited from Object)
Pop()

Удаляет активный запрос CacheRequest из внутреннего стека для текущего потока.Removes the active CacheRequest from the internal stack for the current thread.

Push()

Помещает запрос CacheRequest во внутренний стек состояния, что делает его активным в текущем потоке.Places the CacheRequest on the internal state stack, making it the active request on the current thread.

ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Inherited from Object)

Applies to

See also