我正在开发一个winform应用程序,它将访问作为Windows服务自托管的WCF服务。我使用ChannelFactory而不是service reference。我已成功连接并调用了WCF服务。问题在于当我让应用程序空闲20分钟,然后尝试再次调用时,会收到以下错误消息:“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'.” 我正在寻找最佳实践来管理连接。我目前创建了一个名为PrepareWCFConnection的函数(如下),它检查通道和ChannelFactory的状态。在调用WCF服务之前,我会调用这个方法。有没有更好的处理方法?
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;
}