HOW TO:執行非同步資料服務查詢 (WCF Data Services)
您可以使用 WCF Data Services 用戶端程式庫,以非同步方式執行主從架構的作業,例如,執行查詢與儲存變更。如需詳細資訊,請參閱非同步作業 (WCF Data Services)。
注意
在必須於特定執行緒上叫用回呼的應用程式中,您必須明確地封送 EndExecute 方法的執行。如需詳細資訊,請參閱非同步作業 (WCF Data Services)。
本主題的範例使用 Northwind 範例資料服務,以及自動產生的用戶端資料服務類別。 此服務和用戶端資料類別會在您完成 WCF Data Services 快速入門時建立。
範例
下列範例示範如何透過呼叫 BeginExecute 方法啟動查詢來執行非同步查詢。 內嵌委派會呼叫 EndExecute 方法以顯示查詢結果。
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);
}
}
}