在DataServiceQuery上调用异步的正确方法是什么

时间:2014-09-30 23:28:07

标签: c# wcf async-await

我正在关注这个例子

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>的返回类型错误

在这一行:

query.BeginExecute(OnCustomersQueryComplete, query);

什么是正确的方法,如果可以实现这样的事情。

1 个答案:

答案 0 :(得分:3)

基于the signature of BeginExecute()OnCustomersQueryComplete必须可转换为AsyncCallback,这意味着其返回类型必须为void。此模式称为the Asynchronous Programming Model or APM

我不知道您希望如何处理结果,但我认为最佳选择,如果您可以使用C#5.0,则使用async - await和{{ 3}}:

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