【问题标题】:How to call a web service method in c#如何在 C# 中调用 Web 服务方法
【发布时间】:2010-08-17 10:34:55
【问题描述】:

我想知道如何安全地调用 WCF Web 服务方法。这两种方法都可接受/等效吗?有没有更好的办法?

第一种方式:

public Thing GetThing()
{
    using (var client = new WebServicesClient())
    {
        var thing = client.GetThing();
        return thing;
    }
}

第二种方式:

public Thing GetThing()
{
    WebServicesClient client = null;
    try
    {
        client = new WebServicesClient();
        var thing = client.GetThing();
        return thing;
    }
    finally
    {
        if (client != null)
        {
            client.Close();
        }
    }
}

我想确保客户端已正确关闭和处理。

谢谢

【问题讨论】:

    标签: c# wcf using-statement


    【解决方案1】:

    使用using(没有双关语)就是not recommended,因为即使Dispose() 也可以抛出异常。

    以下是我们使用的几种扩展方法:

    using System;
    using System.ServiceModel;
    
    public static class CommunicationObjectExtensions
    {
        public static void SafeClose(this ICommunicationObject communicationObject)
        {
            if(communicationObject.State != CommunicationState.Opened)
                return;
    
            try
            {
                communicationObject.Close();
            }
            catch(CommunicationException ex)
            {
                communicationObject.Abort();
            }
            catch(TimeoutException ex)
            {
                communicationObject.Abort();
            }
            catch(Exception ex)
            {
                communicationObject.Abort();
                throw;
            }
        }
    
        public static TResult SafeExecute<TServiceClient, TResult>(this TServiceClient communicationObject, 
            Func<TServiceClient, TResult> serviceAction)
            where TServiceClient : ICommunicationObject
        {
            try
            {
                var result = serviceAction.Invoke(communicationObject);
                return result;
            } // try
    
            finally
            {
                communicationObject.SafeClose();
            } // finally
        }
    }
    

    这两个:

    var client = new WebServicesClient();
    return client.SafeExecute(c => c.GetThing());
    

    【讨论】:

    • 我总是创建一个 WebServicesClient 实例并在整个应用程序实例中使用它,这会导致任何问题吗?
    • 谢谢。没想到这么复杂,不过这个看起来不错。
    【解决方案2】:

    第二种方法稍微好一点,因为您要处理可能引发异常的事实。如果您捕获并至少记录了特定异常,那就更好了。

    但是,此代码将阻塞,直到 GetThing 返回。如果这是一个快速操作,那么它可能不是问题,但更好的方法是创建一个异步方法来获取数据。这会引发一个事件以指示完成,并且您订阅该事件以更新 UI(或您需要做的任何事情)。

    【讨论】:

      【解决方案3】:

      不完全是:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-13
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 2014-05-22
        相关资源
        最近更新 更多