1 0 Tag Archives: c#
post icon

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

In the SOA-oriented programming, one of the major mistakes that you make when use WCF services is create an instance of the Transparent Proxy statements within the using statement, as follows:

using(ServiceReference.ClientType client = new ServiceReference.ClientType(“EndpointAddress”))
  {
  //do stuff

 } // <– this line might throw

The error you get is the following:

Type: System.ServiceModel.CommunicationObjectFaultedException.
Message: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

In general, you obtain this error when the service is in a Fault State, so not accessible, but in most cases when the client proxy wasn’t handled properly disposed, so subsequent calls to the first will find the service in faulted state.

To ensure the right management of client proxy disposing, you have to use the Try Catch statement enriched with Finally, as shown below:

ServiceReference.ClientType client = null;

try
{
	client = new ServiceReference.ClientType("EndpointAddress");
	client.Open();

	//do stuff
}
catch (Exception e)
{
	//do stuff
}
finally
{
	if(client != null)
	{
		if (client.State == CommunicationState.Opened)
			client.Close();
		else if (client.State == CommunicationState.Faulted)
			client.Abort();
	}
}

You can find specific references to the following article sull’MSDN: Avoiding Problems with the Using Statement.

November 30th, 2011 @ 01:14