如何在C#中调用Web服务方法
我想知道如何安全地调用 WCF Web 服务方法。这两种方法都可以接受/等效吗?有更好的办法吗?
第一种方式:
public Thing GetThing()
{
using (var client = new WebServicesClient())
{
var thing = client.GetThing();
return thing;
}
}
第二种方式:
public Thing GetThing()
{
WebServicesClient client = null;
try
{
client = new WebServicesClient();
var thing = client.GetThing();
return thing;
}
finally
{
if (client != null)
{
client.Close();
}
}
}
我想确保客户端已正确关闭并处置。
谢谢
I want to know how to safely call a WCF web service method. Are both of these methods acceptable/equivalent? Is there a better way?
1st way:
public Thing GetThing()
{
using (var client = new WebServicesClient())
{
var thing = client.GetThing();
return thing;
}
}
2nd way:
public Thing GetThing()
{
WebServicesClient client = null;
try
{
client = new WebServicesClient();
var thing = client.GetThing();
return thing;
}
finally
{
if (client != null)
{
client.Close();
}
}
}
I want to make sure that the client is properly closed and disposed of.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不建议使用
using
(无双关语) 因为即使是Dispose()
也可能引发异常。这是我们使用的几种扩展方法:
使用这两种方法:
Using
using
(no pun) is not recommended because evenDispose()
can throw exceptions.Here's a couple of extension methods we use:
With these two:
第二种方法稍微好一些,因为您正在应对可能引发异常的事实。如果您捕获并至少记录了特定异常,那就更好了。
但是,此代码将阻塞,直到
GetThing
返回。如果这是一个快速操作,那么它可能不是问题,但更好的方法是创建一个异步方法来获取数据。这会引发一个事件来指示完成,并且您订阅该事件来更新 UI(或您需要执行的任何操作)。The second way is marginally better as you are coping with the fact that an exception might be raised. If you trapped and at least logged the specific exception it would be better.
However, this code will block until
GetThing
returns. If this is a quick operation then it might not be a problem, but otherwise a better approach is to create an asynchronous method to get the data. This raises an event to indicate completion and you subscribe to that event to update the UI (or what ever it is you need to do).不完全是:
请参阅http://geekswithblogs.net/bcaraway/archive/2008/07 /06/123622.aspx
Not quite:
See http://geekswithblogs.net/bcaraway/archive/2008/07/06/123622.aspx