Programming Languages Hacks

Importanti regole per linguaggi di programmazione rilevanti come Java, C, C++, C#…

  • Subscribe

  • Lettori

    I miei lettori abituali

  • Twitter

WCF Client: “Using” best practices

Posted by Ricibald on March 15th, 2013

According to this official Microsoft link you should not use “using” to dispose your wcf client.

Instead use this extension method:

namespace System.ServiceModel
{
    public static class Extensions
    {
        /// <summary>
        /// Release safely your WCF Client
        /// </summary>
        public static void UsingSafe<T>(this T client, Action<T> work)
            where T : ICommunicationObject
        {
            try
            {
                work(client);
            }
            finally
            {
                try
                {
                    client.Close();
                }
                catch (CommunicationException)
                {
                    client.Abort();
                }
                catch (TimeoutException)
                {
                    client.Abort();
                }
                catch (Exception)
                {
                    client.Abort();
                    throw;
                }
            }
        }
    }
}

Usage:

new SomeClient().UsingSafe(channel => {
    channel.Login(username, password);
});

Leave a Reply

You must be logged in to post a comment.