调用WCF服务的最佳做法

时间:2014-02-19 14:58:03

标签: c# wcf

我一直都知道从不在调用WCF服务时使用使用语句

using (Service.YourClientProxy client = new Service.YourClientProxy())
{
    var time = client.Time();
}

所以我总是用它来打电话给服务

YourClientProxy clientProxy = new YourClientProxy();

try
{
   .. use your service
   clientProxy.Close();
}
catch(FaultException)
{
   clientProxy.Abort();
}
catch(CommunicationException)
{
   clientProxy.Abort();
}
catch (TimeoutException)
{ 
   clientProxy.Abort();
}

我一直在阅读och stackoverflow,我已阅读过这篇文章here Service.cs类取自stackoverflow

我想知道以下是否是调用WCF服务的良好做法,这是否真的关闭了服务?

public static class Service<TChannel>
{
    public static ChannelFactory<TChannel> ChannelFactory = new ChannelFactory<TChannel>("*");

    public static TReturn Use<TReturn>(Func<TChannel, TReturn> codeBlock)
    {
        var proxy = (IClientChannel)ChannelFactory.CreateChannel();
        var success = false;
        try
        {
            var result = codeBlock((TChannel)proxy);
            proxy.Close();
            success = true;
            return result;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
    }
}

像这样从客户端调用服务。

        var time = Service<Service.YourServiceChannel>.Use(resultAsync =>
        {
            return resultAsync.TimeAsync();
        });

1 个答案:

答案 0 :(得分:3)

从这篇文章:

http://msdn.microsoft.com/en-us/library/aa355056(v=vs.110).aspx

最佳做法似乎是通过在try块中调用Close来调用Dispose:

try
{
    client.Close();
}
catch (CommunicationException e)
{
    client.Abort();
}
catch (TimeoutException e)
{
    client.Abort();
}
catch (Exception e)
{
    client.Abort();
    throw;
}

您还可以在每个catch块中添加日志记录或其他任何内容。