Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse a client class in WCF after it is faulted

Tags:

wcf

I use WCF for a client server system. When I add a service reference to IService on the server, a proxy class ServiceClient is generated. My code looks like the following:

ServiceClient client = new ServiceClient();
try
{
    client.Operation1();
}
catch(Exception ex)
{
    // Handle Exception
}
try
{
    client.Operation2();
}
catch(Exception ex)
{
    // Handle Exception
}

The problem is that if there is a communication exception in the first call, the client's state changes to Faulted, and I don't know how to reopen it to make the second call. Is there a way to reopen it? or should I create a new one and replace the instance (It doesn't seem like an elegant way)?

like image 212
Andy Avatar asked May 01 '09 12:05

Andy


2 Answers

Once a an ICommunicationObject (your WCF client object) is in a faulted state, the only way to "re-open" it is to create a new one.

ServiceClient client = new ServiceClient();
try
{
    client.Operation1();
}
catch(Exception ex)
{
    if (client.State == CommunicationState.Faulted)
    {
            client.Abort();
            client = new ServiceClient();
    }
}
try
{
    client.Operation2();
}
catch(Exception ex)
{
   // Handle Exception
}
like image 60
Mike_G Avatar answered Nov 03 '22 00:11

Mike_G


If there is a communication exception on the first call which is causing a faulted state, you have to basically "re-create" the WCF client proxy. In your example I would probably do something like:

if (client.State == CommunicationState.Faulted)
    client = new ServiceClient();

This would allow you to "re-open" the connection if it is faulted. It may seem a little overkill, but if you're getting a communication exception on the client side, there's probably something else going on (i.e.: server dead? server not responding?)

Good luck

like image 23
Scott Anderson Avatar answered Nov 03 '22 01:11

Scott Anderson