天天看點

wcf 連接配接出錯的情況下關閉連接配接。

     在.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();
                }
            }
        }
           

繼續閱讀