Export (0) Print
Expand All

How to: Execute Asynchronous Data Service Queries (WCF Data Services)

By using the WCF Data Services client library, you can asynchronously perform client-server operations, such as executing queries and saving changes. For more information, see Asynchronous Operations (WCF Data Services).

Dd756367.note(en-us,VS.100).gifNote:
In an application where the callback must be invoked on a specific thread, you must explicitly marshal the execution of the EndExecute method. For more information, see Asynchronous Operations (WCF Data Services).

The example in this topic uses the Northwind sample data service and autogenerated client data service classes. This service and the client data classes are created when you complete the WCF Data Services quickstart.

Example

The following example shows how to execute an asynchronous query by calling the BeginExecute method to start the 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);
        }
    }
}    

See Also

Community Additions

ADD
Show:
© 2014 Microsoft