c# - WCF 使用匿名方法关闭连接

标签 c# wcf

在我们的项目中,我们使用以下代码进行 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;
  }
}

我们有服务代理类,它有类似的方法

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

通常,由于 channel 也实现了“IDisposable”,您可能会想简单地把它放在一个

using(ICustomer channel = CreateCustomerChannel()) 
{
   // use it
}

block - 不幸的是,这可能会失败,因为当您尝试在您的 channel 上调用 .Close() 时,您很有可能会遇到另一个异常(在这种情况下将无法处理)。

我们的主持人 Marc Gravell 有一个有趣的 blog post (don't(don't(use using))在这个主题上,有一个优雅的问题解决方案。

马克

关于c# - WCF 使用匿名方法关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1344725/

相关文章:

c# - "Microsoft Resource File to COFF Object Conversion Utility has stopped working"编译时出错

php - 如何从 PHP 调用 RESTful WCF 服务

c# - WCF 服务方法参数,指定 bool 值

c# - Visual Studios C# - 从数据库中添加、读取和删除数据

c# - 等到文件完全写入

c# - 连接尝试失败,因为连接方在一段时间后没有正确响应。从 C# 调用存储过程时

c# - 如何使用 C# .NET 'Mark as read ' GMail 的邮件?

wcf - 在 Azure 上的本地主机上使用 WCF

c# - 使用 Silverlight/IIS 的双工轮询的可扩展性

asp.net - WCF 服务的负载测试