2016-03-03 42 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線程中強制觸發客戶端關閉。