C# 如何在c中调用web服务方法#

C# 如何在c中调用web服务方法#,c#,wcf,using-statement,C#,Wcf,Using Statement,我想知道如何安全地调用WCF web服务方法。这两种方法都可以接受/等效吗?有更好的办法吗 第一条路: public Thing GetThing() { using (var client = new WebServicesClient()) { var thing = client.GetThing(); return thing; } } 第二种方式: public Thing GetThing() { WebService

我想知道如何安全地调用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();
        }
    }
}
我想确保客户已正确关闭和处置

感谢使用
使用
(没有双关语)是因为即使
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
    }
}
不完全是:

  • 第二种方式不处理()您的客户
  • 如果出现错误,使用将无法正确清理 看

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


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

      我始终创建一个WebServicesClient实例,并在整个应用程序实例中使用它,这会导致任何问题吗?谢谢。没想到会这么复杂,但这看起来不错。
      var client = new WebServicesClient();
      return client.SafeExecute(c => c.GetThing());