我正在异步调用soap服务,但仍然需要关闭soap客户端连接。以前的帖子没有多少帮助:How to close Client Proxy with Async Call WCF
到目前为止,我的代码如下。
下面的方法(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 :(得分:0)
我建议使用全局WebServiceClient或ApiClient,并在两个线程中执行GetResponse和CloseClient。这样,即使您正在等待响应,也可以在CloseClient线程中强制触发客户端关闭。