【问题标题】:How to close a soap client while making async calls?如何在进行异步调用时关闭肥皂客户端?
【发布时间】:2016-06-16 09:03:45
【问题描述】:

我正在异步调用一个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;
    }
}

知道我错过了什么吗? 谢谢

【问题讨论】:

  • 我知道这是一篇旧帖子,您可能已经弄清楚它出了什么问题,但只是出于好奇,当它没有异步时,您如何等待 GetResponse 并且也是你没有“等待”“GetFieldListAsync”的问题是因为它退出了你的范围并且连接被杀死了?

标签: c# web-services asynchronous soap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多