Язык

DataServiceContext.EndExecute<TElement>(IAsyncResult) Метод

Определение

Вызывается для завершения BeginExecute<TElement>(Uri, AsyncCallback, Object).

public:
generic <typename TElement>
 System::Collections::Generic::IEnumerable<TElement> ^ EndExecute(IAsyncResult ^ asyncResult);
public System.Collections.Generic.IEnumerable<TElement> EndExecute<TElement>(IAsyncResult asyncResult);
member this.EndExecute : IAsyncResult -> seq<'Element>
Public Function EndExecute(Of TElement) (asyncResult As IAsyncResult) As IEnumerable(Of TElement)

Параметры типа

TElement

Тип, возвращаемый запросом.

Параметры

asyncResult
IAsyncResult

Объект IAsyncResult.

Возвращаемое значение

IEnumerable<TElement>

Результаты, возвращаемые операцией запроса.

Исключения

Когда asyncResult есть null.

Когда asyncResult не произошло из этого DataServiceContext экземпляра.

–или–

Метод EndExecute<TElement>(IAsyncResult) был вызван ранее.

При возникновении ошибки во время выполнения запроса или при преобразовании содержимого сообщения ответа в объекты.

Примеры

В следующем примере показано, как выполнить асинхронный запрос, вызвав BeginExecute метод для запуска запроса. Встроенный EndExecute делегат вызывает метод для отображения результатов запроса. В этом примере используется DataServiceContext средство "Добавить справочник по службе" на основе службы данных Northwind, которая создается при завершении службы данных WCF.

public static void BeginExecuteCustomersQuery()
{
    // Create the DataServiceContext using the service URI.
    NorthwindEntities context = new NorthwindEntities(svcUri);

    // Define the query to execute asynchronously that returns
    // all customers with their respective orders.
    DataServiceQuery<Customer> query = (DataServiceQuery<Customer>)(from cust in context.Customers.Expand("Orders")
                                       where cust.CustomerID == "ALFKI"
                                       select cust);

    try
    {
        // Begin query execution, supplying a method to handle the response
        // and the original query object to maintain state in the callback.
        query.BeginExecute(OnCustomersQueryComplete, query);
    }
    catch (DataServiceQueryException ex)
    {
        throw new ApplicationException(
            "An error occurred during query execution.", ex);
    }
}

// Handle the query callback.
private static void OnCustomersQueryComplete(IAsyncResult result)
{
    // Get the original query from the result.
    DataServiceQuery<Customer> query =
        result as DataServiceQuery<Customer>;

    foreach (Customer customer in query.EndExecute(result))
    {
        Console.WriteLine("Customer Name: {0}", customer.CompanyName);
        foreach (Order order in customer.Orders)
        {
            Console.WriteLine("Order #: {0} - Freight $: {1}",
                order.OrderID, order.Freight);
        }
    }
}
Public Shared Sub BeginExecuteCustomersQuery()
    ' Create the DataServiceContext using the service URI.
    Dim context = New NorthwindEntities(svcUri)

    ' Define the delegate to callback into the process
    Dim callback As AsyncCallback = AddressOf OnCustomersQueryComplete

    ' Define the query to execute asynchronously that returns 
    ' all customers with their respective orders.
    Dim query As DataServiceQuery(Of Customer) =
    context.Customers.Expand("Orders")

    Try
        ' Begin query execution, supplying a method to handle the response
        ' and the original query object to maintain state in the callback.
        query.BeginExecute(callback, query)
    Catch ex As DataServiceQueryException
        Throw New ApplicationException(
                "An error occurred during query execution.", ex)
    End Try
End Sub
' Handle the query callback.
Private Shared Sub OnCustomersQueryComplete(ByVal result As IAsyncResult)
    ' Get the original query from the result.
    Dim query As DataServiceQuery(Of Customer) =
        CType(result.AsyncState, DataServiceQuery(Of Customer))

    ' Complete the query execution.
    For Each customer As Customer In query.EndExecute(result)
        Console.WriteLine("Customer Name: {0}", customer.CompanyName)
        For Each order As Order In customer.Orders
            Console.WriteLine("Order #: {0} - Freight $: {1}",
                    order.OrderID, order.Freight)
        Next
    Next
End Sub

Комментарии

В соответствии со стандартным асинхронным шаблоном начала предоставленный обратный вызов вызывается при извлечении результатов запроса. Дополнительные сведения см. в статье "Асинхронные операции".

При вызове обратного вызова все результаты были считываются из HTTP-потока, но они не обработаны; Не было материализовано или изменено локальных объектов, а разрешение удостоверений не произошло. При EndExecute вызове DataServiceResponse создается и возвращается, но результаты по-прежнему не обрабатываются. Разрешение удостоверений, материализация объектов и манипуляция происходят только в том случае, если пользователь перечисляет результаты.

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

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