当“返回”时会发生什么?从“using”内部调用堵塞?
如果我有一个带有像这样的 using 块的方法...
public IEnumerable<Person> GetPersons()
{
using (var context = new linqAssignmentsDataContext())
{
return context.Persons.Where(p => p.LastName.Contans("dahl"));
}
}
...从 using 块中返回值,IDisposable 对象是否仍然会被释放?
If I have a method with a using block like this...
public IEnumerable<Person> GetPersons()
{
using (var context = new linqAssignmentsDataContext())
{
return context.Persons.Where(p => p.LastName.Contans("dahl"));
}
}
...that returns the value from within the using block, does the IDisposable object still get disposed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,确实如此。对象的处置发生在finally 块中,即使面对返回调用,该块也会执行。它本质上扩展到以下代码
Yes it does. The disposing of the object occurs in a finally block which executes even in the face of a return call. It essentially expands out to the following code
来自MSDN 文档:
所以该对象总是被释放。除非你拔掉电源线。
From the MSDN documentation:
So the object is always disposed. Unless you plug out the power cable.