正确调用WCF服务的异步方法

时间:2014-09-16 14:24:50

标签: c# wcf asynchronous async-await windows-8.1

我有WCF服务,它返回对象集合。

他正在编写我开始使用的代码(我不确定它是否正确):

List<AxaptaServiceReference.Inspection> remoteInspections = (await proxy.GetInspectionsByInspectorAsync(App._winlogin)).ToList<AxaptaServiceReference.Inspection>();

我需要将此调用移至单独的类:

public class AxGateWay
{
    public async List<AxaptaServiceReference.Inspection> GetInspections(string _inspector) 
    {
        AxaptaServiceReference.AxaptaWebServiceClient proxy = new AxaptaServiceReference.AxaptaWebServiceClient();

        List<AxaptaServiceReference.Inspection> remoteInspections = (await task).ToList<AxaptaServiceReference.Inspection>();
        return remoteInspections;
    }
}

编译器告诉我异步方法必须返回Task(或Task&lt;&gt;)。

如果我想确保在Web服务返回数据时我的代码会等待,我该如何重写我的方法以及此方法调用的方式。

1 个答案:

答案 0 :(得分:3)

  

编译器告诉我异步方法必须返回Task(或Task&lt;&gt;)。

然后,您将async方法返回Task<>

public async Task<List<AxaptaServiceReference.Inspection>> GetInspectionsAsync(string _inspector) 
{
  List<AxaptaServiceReference.Inspection> remoteInspections = ...;
  return remoteInspections;
}

是的,这会导致您的来电者使用await,这意味着他们必须成为async等等。async将通过您的代码库“增长”,就像这样;这种“成长”是自然的,应该被接受。

相关问题