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

前端 未结 26 1744
余生分开走
余生分开走 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:31

    I have my own wrapper for a channel which implements Dispose as follows:

    public void Dispose()
    {
            try
            {
                if (channel.State == CommunicationState.Faulted)
                {
                    channel.Abort();
                }
                else
                {
                    channel.Close();
                }
            }
            catch (CommunicationException)
            {
                channel.Abort();
            }
            catch (TimeoutException)
            {
                channel.Abort();
            }
            catch (Exception)
            {
                channel.Abort();
                throw;
            }
    }
    

    This seems to work well and allows a using block to be used.

提交回复
热议问题