Cómo: Ejecutar consultas de servicio de datos asincrónicos (WCF Data Services)

Al usar la biblioteca de cliente de WCF Data Services , puede realizar operaciones cliente-servidor, como ejecutar consultas y guardar cambios, de forma asincrónica. Para obtener más información, vea Operaciones asincrónicas (WCF Data Services).

Dd756367.note(es-es,VS.100).gifNota:
En una aplicación donde se debe invocar la devolución de llamada en un subproceso concreto, debe calcular explícitamente las referencias de la ejecución del método EndExecute.Para obtener más información, vea Operaciones asincrónicas (WCF Data Services).

En el ejemplo de este tema se utiliza el servicio de datos de ejemplo Northwind y se generan automáticamente las clases del servicio de datos del cliente. Se crean este servicio y las clases de datos del cliente al completar el tutorial rápido de WCF Data Services.

Ejemplo

En el siguiente ejemplo se muestra cómo ejecutar una consulta asincrónica llamando al método BeginExecute para iniciar la consulta. El delegado alineado llama al método EndExecute para mostrar los resultados de la consulta.

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
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);
        }
    }
}    

Vea también

Otros recursos

Biblioteca de cliente de WCF Data Services