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)?
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With