using 语句和 WCF 客户端的问题
我一直将所有调用 WCF 调用的代码包装在 using 语句中,认为该对象将被正确处理。当我在谷歌上搜索异常“位于 .. 的 Http 服务太忙”时,我发现了此链接 http://msdn.microsoft.com/en-us/library/aa355056.aspx 表示不应在类型代理中使用 using 语句。这是真的吗?我想我的代码发生了很大的变化(叹气)。这个问题只出现在类型代理中吗?
示例代码:
private ServiceClient proxy;
using(proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc")){
string result = proxy.Method();
}
I've been wrapping all the code that invoke WCF calls within an using statement in a thought that the object will be disposed properly. When I'm googling for an exception "Http service located at .. is too busy" I found this link http://msdn.microsoft.com/en-us/library/aa355056.aspx that says should not use using statement in typed proxies. Is that really true? I think I got a big code change (sigh). Is this problem comes only in typed proxies?
Sample code:
private ServiceClient proxy;
using(proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc")){
string result = proxy.Method();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题的核心是:在
using
块的末尾(这通常是一个非常好的主意!),WCF 代理将被释放。但是,在处置 WCF 代理期间,可能会发生异常 - 这将导致应用程序行为异常。由于这是在using
块的末尾隐式完成的,因此您甚至可能无法真正看到错误发生的位置。因此,通常,Microsoft 会推荐这样的模式:
您需要调用显式调用 proxy.Close() 方法,并准备好处理该调用可能发生的任何异常。
The core of the problem is: at the end of your
using
block (which generally is a very good idea to have!), the WCF proxy will be disposed. However, during disposing of the WCF proxy, exceptions can occur - and those will cause the app to misbehave. Since this is done implicitly at the end of theusing
block, you might not even really see where the error occurs.So typically, Microsoft recommends a pattern something like this:
You need to call the
proxy.Close()
method explicitly and be prepared to handle any exceptions that might occur from that call, too.将代理操作和实例化调用包装在实现 IDisposable 的类中。处置时,检查代理的状态属性,并在关闭前清理通道。
Wrap the proxy operation and instantiation calls up in a class implementing
IDisposable
. When disposing, check the state property of the proxy and tidy up the channel before closing.我喜欢这个博客上“Eric”的评论中的方法(类似于另一篇文章:http://redcango.blogspot.com/2009/11/using-using-statement-with-wcf-proxy.htm):
“就我个人而言,我喜欢为客户端创建自己的分部类并重写 Dispose() 方法。这使我可以像平常一样使用“using”块。
I like the approach from the comment from "Eric" on this blog (which is similar to another article: http://redcango.blogspot.com/2009/11/using-using-statement-with-wcf-proxy.htm):
"Personally, I like to create my own partial class for the client and override the Dispose() method. This allows me to use the ‘using’ block as I normally would.