DataServiceContext.EndExecute<TElement>(IAsyncResult) Método

Definição

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)

Parâmetros de tipo

TElement

O tipo retornado pela consulta.

Parâmetros

asyncResult
IAsyncResult

IAsyncResult objeto.

Retornos

IEnumerable<TElement>

Os resultados retornados pela operação de consulta.

Exceções

Quando asyncResult é null.

Quando asyncResult não se originou dessa DataServiceContext instância.

-ou-

O EndExecute<TElement>(IAsyncResult) método foi chamado anteriormente.

Quando um erro é gerado durante a execução da solicitação ou quando ele converte o conteúdo da mensagem de resposta em objetos.

Exemplos

O exemplo a seguir mostra como executar uma consulta assíncrona chamando o BeginExecute método para iniciar a consulta. O delegado embutido chama o EndExecute método para exibir os resultados da consulta. Este exemplo usa o DataServiceContext gerado pela ferramenta Adicionar Referência de Serviço com base no serviço de dados Northwind, que é criado quando você conclui os Serviços de Dados do 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

Comentários

De acordo com o padrão assíncrono de início-fim padrão, o retorno de chamada fornecido é invocado quando os resultados da consulta são recuperados. Para obter mais informações, consulte Operações assíncronas.

Quando o retorno de chamada é invocado, todos os resultados foram lidos do fluxo HTTP, mas eles não foram processados; nenhum objeto voltado para o usuário local foi materializado ou modificado e a resolução de identidade não ocorreu. Quando EndExecute é invocado, um DataServiceResponse é criado e retornado, mas os resultados ainda não foram processados. A resolução de identidade, a materialização do objeto e a manipulação ocorrem somente quando o usuário enumera os resultados.

Aplica-se a

Confira também