Procedura: eseguire query asincrone sul servizio dati (WCF Data Services)How to: Execute Asynchronous Data Service Queries (WCF Data Services)

Tramite la libreria client di WCF Data ServicesWCF Data Services è possibile eseguire in modo asincrono operazioni client-server, ad esempio query e salvataggio di modifiche.By using the WCF Data ServicesWCF Data Services client library, you can asynchronously perform client-server operations, such as executing queries and saving changes. Per ulteriori informazioni, vedere operazioni asincrone.For more information, see Asynchronous Operations.

Nota

In un'applicazione in cui il callback deve essere richiamato su un thread specifico, è necessario effettuare il marshalling in modo esplicito del metodo EndExecute.In an application where the callback must be invoked on a specific thread, you must explicitly marshal the execution of the EndExecute method. Per ulteriori informazioni, vedere operazioni asincrone.For more information, see Asynchronous Operations.

Nell'esempio riportato in questo argomento vengono usati il servizio dati Northwind di esempio e le classi del servizio dati client generate automaticamente.The example in this topic uses the Northwind sample data service and autogenerated client data service classes. Questo servizio e le classi di dati client vengono create quando si completa la Guida rapida di WCF Data Services.This service and the client data classes are created when you complete the WCF Data Services quickstart.

EsempioExample

Nell'esempio seguente viene illustrato come eseguire una query asincrona chiamando il metodo BeginExecute per l'avvio della query.The following example shows how to execute an asynchronous query by calling the BeginExecute method to start the query. Il delegato inline chiama il metodo EndExecute per visualizzare i risultati della query.The inline delegate calls the EndExecute method to display the query results.

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

Vedere ancheSee Also

Libreria client WCF Data ServicesWCF Data Services Client Library