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

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

    Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.

    So, to get around this, I've employed a solution that mixes the best of both worlds.

    void IDisposable.Dispose()
    {
        bool success = false;
        try 
        {
            if (State != CommunicationState.Faulted) 
            {
                Close();
                success = true;
            }
        } 
        finally 
        {
            if (!success) 
                Abort();
        }
    }
    

提交回复
热议问题