我正在异步调用 soap 服务,但卡在需要关闭 soap 客户端连接的位置。上一篇文章也没有太多帮助: 如何使用异步调用 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;
}
}
知道我错过了什么吗?谢谢
我建议有一个全局WebServiceClient或ApiClient,并在两个线程中执行GetResponse和CloseClient。这样,即使您正在等待响应,您也可以在 CloseClient 线程中强制触发客户端关闭。