2014-09-30 42 views
-2

我下面這個例子什麼合適的方法來調用異步於化DataServiceQuery

http://msdn.microsoft.com/en-us/library/dd756367(v=vs.110).aspx

但我修改它看起來像這樣

 public static void BeginExecuteCustomersQuery() 
     { 
     DataServiceQuery<ASHPersonify.OrderDetailInfo> query = 
     (DataServiceQuery<ASHPersonify.OrderDetailInfo>) 
     (SvcClient.Ctxt.OrderDetailInfos 
     .Where(a =>a.ShipMasterCustomerId == "pppp" 
       && a.ShipSubCustomerId == 0 
       && a.LineStatusCode == "A")); 

       try 
       { 
        query.BeginExecute(OnCustomersQueryComplete, query); 
       } 
       catch (DataServiceQueryException ex) 
       { 
        throw new ApplicationException(
         "An error occurred during query execution.", ex); 
       } 
     } 


     public List<ASHPersonify.OrderDetailInfo> OnCustomersQueryComplete(IAsyncResult result) 
     { 
       // Get the original query from the result. 
       DataServiceQuery<ASHPersonify.OrderDetailInfo> query = 
        result as DataServiceQuery<ASHPersonify.OrderDetailInfo>; 

       return query.EndExecute(result).ToList(); 

     } 

,現在我收到此錯誤:

System.Collections.Generic.List<ASH_QIS.ASHPersonify.OrderDetailInfo> has the wrong return type

就行了:

query.BeginExecute(OnCustomersQueryComplete, query); 

什麼是正確的方式,如果它可能實現這樣的東西。

+0

,願你有爲什麼有-2的解釋 – 2014-10-01 15:05:38

回答

0

基於the signature of BeginExecute(),OnCustomersQueryComplete必須轉換爲AsyncCallback,這意味着它的返回類型必須是void。這種模式被稱爲the Asynchronous Programming Model or APM

我不知道你怎麼能指望有結果的工作,但我認爲最好的選擇,如果你可以使用C#5.0是使用async - awaitTask.Factory.FromAsync()

public static Task<IEnumerable<T>> ExecuteAsync<T>(this DataServiceQuery<T> query) 
{ 
    return Task.Factory.FromAsync(query.BeginExecute, query.EndExecute, null); 
} 

… 

public static Task<IEnumerable<ASHPersonify.OrderDetailInfo>> ExecuteCustomersQueryAsync() 
{ 
    var query = 
     (DataServiceQuery<ASHPersonify.OrderDetailInfo>) 
     (SvcClient.Ctxt.OrderDetailInfos 
      .Where(a =>a.ShipMasterCustomerId == "pppp" 
       && a.ShipSubCustomerId == 0 
       && a.LineStatusCode == "A")); 

    try 
    { 
     return await query.ExecuteAsync(); 
    } 
    catch (DataServiceQueryException ex) 
    { 
     throw new ApplicationException(
      "An error occurred during query execution.", ex); 
    } 
}