Closing Down Channels

When using channels, eventually the time comes to say goodbye. You are not going to send any more messages, and you want to close down as gracefully as possible. So you call channel.Close. If it throws, your application goes down since you didn’t add a try/catch clause and you are S.O.L. Maybe you’ve written a chatty peer to peer application and you get a message such as:

System.ServiceModel.ProtocolException: The channel received an unexpected input message with Action ‘my action’ while closing. You should only close your channel when you are not expecting any more input messages.

Or perhaps your channel faulted due to network inactivity or some other transient error. The bottom line is that there are a number of situations where an exception from channel.Close is expected and should be handled gracefully. In these cases, the expected exceptions from close could be subclasses of CommunicationException and TimeoutException. So a more robust call to Close() would look like:
try
{
  
Console.WriteLine(wcfClient.Add(4, 6));
   channel.Close();
}
catch (TimeoutException timeout)
{
  
// Handle the timeout exception
   channel.Abort();
}
catch (CommunicationException communicationException)
{
  
// Handle the communication exception
   channel.Abort();
}

One last note: just because some of our CommunicationObjects are marked as IDisposable, doesn’t mean that you should jump on the using() statement with them. Please read about the issues involved with using and Communication Objects first.

Leave a Reply

Your email address will not be published. Required fields are marked *