1

I have always learned that never use using statement when calling WCF Service like this

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

So I am always using this to call Service

YourClientProxy clientProxy = new YourClientProxy();

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

I have been reading och stackoverflow and I have read this post here Service.cs class taken from stackoverflow

I would like to know if this below is a good practice to call WCF service and does this really close the service?

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();
            }
        }
    }
}

Invoking service from client like this.

        var time = Service<Service.YourServiceChannel>.Use(resultAsync =>
        {
            return resultAsync.TimeAsync();
        });
Community
  • 1
  • 1
user3046164
  • 149
  • 1
  • 6
  • 14
  • I made a reference and read that post and it wasn't clear to me what was the best practice. I was also asking if that code sample that I was referring really closed the connection. – user3046164 Feb 19 '14 at 15:18

1 Answers1

4

From this article:

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

It seems the best practice is to call Dispose is by calling Close in a try block:

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

You can also add logging or whatever else in each catch block.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101