在.NET Framework中,一个资源(尤其是非托管资源)通常都需要实现IDisposable接口,这样就可以通过using释放占有的资源,但是如果using块中的语句抛出了异常,资源可能就无法正常释放。如果是连接就会一直占用着连接和端口,浪费资源,降低系统的性能。在WCF中远程方法抛出异常,则就会导致客户端资源没法直接使用Close方法释放资源。这时可采用Abort方法关闭连接。
如果是自己通过ChannelFactory采用硬编码的方式构造通信信道,并且返回契约的话,则可以通过 ICommunicationObject的接口释放连接资源,这是因为所有的客户端对象都实现了ICommunicationObject接口。下面是一个简单例子:
//构造连接通道
public static ISeatManageService CreateChannelService()
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
binding.MaxReceivedMessageSize = int.MaxValue;
string endPointAddress = readerOperateEndpointAddress + "SeatManageDateService/";
ChannelFactory<ISeatManageService> proxy = new ChannelFactory<ISeatManageService>(binding, new EndpointAddress(endPointAddress));
foreach (OperationDescription op in proxy.Endpoint.Contract.Operations)
{
DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
ISeatManageService obj = proxy.CreateChannel();
return obj;
}
客户端远程调用:
public static HardAdvertInfo GetHardAdvertByNum(string num)
{
IWCFService.ISeatManageService seatService = WcfAccessProxy.ServiceProxy.CreateChannelService();
bool error = false;
try
{
return seatService.GetHardAdvertByNum(num);
}
catch (FaultException ex)
{
error = true;
return null;
}
finally
{
ICommunicationObject ICommObjectService = seatService as ICommunicationObject;//释放连接
try
{
if (ICommObjectService.State == CommunicationState.Faulted)
{//如果通道出现异常释放
ICommObjectService.Abort();
}
else
{
ICommObjectService.Close();
}
}
catch
{
ICommObjectService.Abort();
}
}
}