What is the best workaround for the WCF client `using` block issue?

前端 未结 26 1697
余生分开走
余生分开走 2020-11-22 00:03

I like instantiating my WCF service clients within a using block as it\'s pretty much the standard way to use resources that implement IDisposable:

26条回答
  •  一生所求
    2020-11-22 00:15

    Use an extension method:

    public static class CommunicationObjectExtensions
    {
        public static TResult MakeSafeServiceCall(this TService client, Func method) where TService : ICommunicationObject
        {
            TResult result;
    
            try
            {
                result = method(client);
            }
            finally
            {
                try
                {
                    client.Close();
                }
                catch (CommunicationException)
                {
                    client.Abort(); // Don't care about these exceptions. The call has completed anyway.
                }
                catch (TimeoutException)
                {
                    client.Abort(); // Don't care about these exceptions. The call has completed anyway.
                }
                catch (Exception)
                {
                    client.Abort();
                    throw;
                }
            }
    
            return result;
        }
    }
    

提交回复
热议问题