2016-03-03 45 views
0

我正在异步调用soap服务,但停留在需要关闭soap客户端连接的地方。以前的帖子没什么帮助:How to close Client Proxy with Async Call WCF如何在进行异步调用时关闭soap客户端?

以下是我的代码到目前为止。

下面的方法(GetFieldList(....)调用带有请求参数的泛型方法ApiClient.GetResponse(....),并调用什么样的服务

public async Task<ServiceReference.GetFieldListResponse> GetFieldList(string identifier) 
    { 
     var request = new GetFieldListRequest 
     { 
      Header = new Header {Username = ApiSettings.Instance.ApiToken}, 
      AGroup = "", 
      IdType = "", 
      Id = "" 
     }; 
     var response = await ApiClient.GetResponse(request, (c) => c.GetFieldListAsync(request.Header, request.Id, request.IdType, request.AGroup)); 
     return response; 
    } 

在下面的方法,我已经注释掉finally块,因为连接被关闭之前的响应返回给调用方法。

public class ApiClient 
{ 

    public static TResponse GetResponse<TResponse, TRequest>(TRequest request, 
      Func<SoapClient, TResponse> handler, 
      string apiMethodName = "") 
    where TResponse : class 
    { 
     Debug.WriteLine("Calling: " + typeof(TRequest).Name); 
     if (string.IsNullOrEmpty(apiMethodName)) 
     { 
      apiMethodName = typeof(TRequest).Name.Replace("Request", string.Empty); 
     } 

     // creates a soap connection 
     var client = WebServiceClient.CreateServiceInstance(); 
     TResponse response = null; 
     try 
     { 
      //webservice call is invoked here 
      response = handler(client); 
     } 
     catch (FaultException exception) 
     { 
      throw new ApiException(string.Format("Api error on {0}.", apiMethodName), exception); 
     } 

     //if this finally block is not commented, connection is closed before a response was returned to the calling method. 
     //finally 
     //{ 
     // client.Close(); 
     //} 

     return response; 
    } 
} 

任何想法,我缺少的是什么? 感谢

+0

我知道这是一个旧的帖子,你可能已经找到了它出了什么问题,但出于好奇,当没有异步时,你如何能够等待GetResponse,也是你的问题而不是“等待”的“GetFieldListAsync”,因为它退出你的范围和连接被杀害? –

回答

0

我建议有一个全局的WebServiceClient或ApiClient,并在两个线程中执行GetResponse和CloseClient。这样,即使您在等待响应,您也可以在CloseClient线程中强制触发客户端关闭。