c# – WCF使用匿名方法关闭连接
发布时间:2020-12-16 01:32:01 所属栏目:百科 来源:网络整理
导读:在我们的项目中,我们使用以下代码进行WCF调用. // In generated Proxy we have..public static ICustomer Customer{ get { ChannelFactoryICustomer factory = new ChannelFactoryICustomer("Customer"); factory.Endpoint.Behaviors.Add((System.ServiceMod
在我们的项目中,我们使用以下代码进行WCF调用.
// In generated Proxy we have.. public static ICustomer Customer { get { ChannelFactory<ICustomer> factory = new ChannelFactory<ICustomer>("Customer"); factory.Endpoint.Behaviors.Add((System.ServiceModel.Description.IEndpointBehavior)new ClientMessageInjector()); ICustomer channel = factory.CreateChannel(); return channel; } } 我们有Service Proxy类,它有类似的方法 public static Datatable GetCustomerDetails(int id) { return Services.Customer.GetCustomerDetails(id); } public static void .SaveCustomerDetails (int id) { Services.Customer.SaveCustomerDetails(id) ; } 等…我们用来打电话. 最近我们发现我们需要“关闭”wcf连接,我们正试图找出去做而不要求我们的开发人员改变太多的代码. 请向我们提供一些有助于我们实现这一目标的建议 解决方法
对于这种情况,公认的“最佳做法”将是这样的:
// create your client ICustomer channel = CreateCustomerClient(); try { // use it channel.GetCustomerDetails() .... (more calls) // close it channel.Close(); } catch(CommunicationException commEx) { // a CommunicationException probably indicates something went wrong // when closing the channel --> abort it channel.Abort(); } 通常情况下,由于频道也实现了“IDisposable”,你可能只想把它放在一个 using(ICustomer channel = CreateCustomerChannel()) { // use it } 阻止 – 不幸的是,这可能会爆炸,因为很有可能在你的频道上试图调用.Close()时,你会得到另一个异常(在这种情况下会被处理). 我们的主持人Marc Gravell在这个主题上有一个有趣的blog post (don’t(don’t(use using)),有一个优雅的问题解决方案. 渣 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |