Recovering from a CommunicationObjectFaultedException in WCF

后端 未结 1 1835
礼貌的吻别
礼貌的吻别 2021-01-30 12:08

I have a client app that tries every 10 seconds to send a message over a WCF web service. This client app will be on a computer on board a ship, which we know will have spotty

相关标签:
1条回答
  • 2021-01-30 12:33

    Client service proxies cannot be reused once they have faulted. You must dispose of the old one and recreate a new one.

    You must also make sure you close the client service proxy properly. It is possible for a WCF service proxy to throw an exception on close, and if this happens the connecting is not closed, so you must abort. Use the "try{Close}/catch{Abort}" pattern. Also bear in mind that the dispose method calls close (and hence can throw an exception from the dispose), so you can't just use a using like with normal disposable classes.

    For example:

    try
    {
        if (yourServiceProxy != null)
        {
            if (yourServiceProxy.State != CommunicationState.Faulted)
            {
                yourServiceProxy.Close();
            }
            else
            {
                yourServiceProxy.Abort();
            }
        }
    }
    catch (CommunicationException)
    {
        // Communication exceptions are normal when
        // closing the connection.
        yourServiceProxy.Abort();
    }
    catch (TimeoutException)
    {
        // Timeout exceptions are normal when closing
        // the connection.
        yourServiceProxy.Abort();
    }
    catch (Exception)
    {
        // Any other exception and you should 
        // abort the connection and rethrow to 
        // allow the exception to bubble upwards.
        yourServiceProxy.Abort();
        throw;
    }
    finally
    {
        // This is just to stop you from trying to 
        // close it again (with the null check at the start).
        // This may not be necessary depending on
        // your architecture.
        yourServiceProxy = null;
    }
    

    There is a blog article about this here

    0 讨论(0)
提交回复
热议问题