CacheRequest Класс

Определение

Определяет свойства и шаблоны, которые платформа автоматизации пользовательского интерфейса кэширует при получении элемента AutomationElement.

public ref class CacheRequest sealed
public sealed class CacheRequest
type CacheRequest = class
Public NotInheritable Class CacheRequest
Наследование
CacheRequest

Примеры

В следующем примере показано, как использовать Activate для кэширования шаблонов и свойств.

/// <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 для кэширования шаблонов и свойств.

/// <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

Комментарии

Для получения свойств и шаблонов с помощью модель автоматизации пользовательского интерфейса требуются межпроцессные вызовы, которые могут снизить производительность. Кэширование значений свойств и шаблонов в пакетной операции позволяет повысить производительность приложения.

Создайте новый запрос кэша, вызвав конструктор класса. Запрос заполняется неоднократными вызовами Add метода .

Только один CacheRequest может быть активным. Существует два способа активации запроса:

  • Вызовите Activate по запросу. При этом запрос отправляется в стек, и при удалении объекта он выкашывается. Чтобы обеспечить удаление даже при возникновении исключения, используйте возвращаемое значение из Activateusing блока (Using в Visual Basic).

  • Поместите запрос во внутренний стек, вызвав .Push Активен только самый верхний запрос в стеке, и он должен быть следующим, удаленным из стека с помощью Pop. При выводе запроса он будет отключен.

модель автоматизации пользовательского интерфейса элементы, полученные при активном запросе, будут иметь кэшированные значения указанных свойств и шаблонов.

Конструкторы

CacheRequest()

Инициализирует новый экземпляр класса CacheRequest.

Свойства

AutomationElementMode

Возвращает или задает значение, указывающее, должны ли возвращаемые элементы содержать полные ссылки на базовый пользовательский интерфейс или только кэшированные сведения.

Current

Возвращает запрос CacheRequest, который является активным в текущем потоке.

TreeFilter

Возвращает или задает значение, указывающее представление дерева элементов модель автоматизации пользовательского интерфейса для использования при кэшировании.

TreeScope

Возвращает или задает значение, которое показывает, выполняется ли кэширование только для корня вложенного дерева или также для дочерних элементов и потомков.

Методы

Activate()

Определяет данный запрос CacheRequest как активную спецификацию для элементов, которые возвращаются, когда элемент AutomationElement запрашивается в том же потоке.

Add(AutomationPattern)

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

Add(AutomationProperty)

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

Clone()

Создает копию данного объекта CacheRequest.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

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

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Pop()

Удаляет активный запрос CacheRequest из внутреннего стека для текущего потока.

Push()

Помещает запрос CacheRequest во внутренний стек состояния, что делает его активным в текущем потоке.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел