I am working on an winform application that will access a WCF service self-hosted as a windows service. I am using the ChannelFactory instead of the service reference. I have been successful in connecting and calling the WCF service. The issue is when I let the application remain idle for 20 minutes and then try to make another call. I receive the following error:
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9489970'."
I am looking for the best practice on managing the connection. I currently have created a function called PrepareWCFConnection (see below) that checks state of the channel and the ChannelFactory. I call this method before I make any calls to the WCF services. Is there a better way of handling this?
public bool PrepareWCFConnection()
{
if ((channelFactory == null) ||
(channelFactory.State == CommunicationState.Faulted) ||
(channelFactory.State != CommunicationState.Opened))
{
channelFactory = new ChannelFactory<IService1>(new NetTcpBinding(), endpointAddress);
}
if ((proxy == null) ||
(((IClientChannel)proxy).State == CommunicationState.Faulted) ||
(((IClientChannel)proxy).State != CommunicationState.Opened))
{
proxy = channelFactory.CreateChannel(endpointAddress);
((IClientChannel)proxy).Open();
}
return true;
}
If you want to reuse an existing channel you need to Keep the channel alive by pinging the service every 9 minutes.I think the default receive timeout is 10 minutes, so the channel will be disconnected if it is kept idle beyond this.Or you can use reliable sessions to keep channels alive.
If you don't need to callback on the same channel , it is better you close the channel once you are done and recreate a new channel for every service operation.It is not expensive to create channels.You can cache the channel factory , but create channels for every call.
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