在我们的项目中,我们使用以下代码进行 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 有一个有趣的话题博客文章(不要(不要(使用使用)) http://marcgravell.blogspot.com/2008/11/dontdontuse-using.html就主题而言,有一个优雅的解决方案。
Marc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)