Will a IDisposable be disposed if the using block returns?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 09:27:01

问题


For example

using(var something = GetSomething())
{
    something.DoSomething();
    if(something.IsX()) return true;
}
return false;

回答1:


Yes, absolutely. The Dispose method is called however the using statement is executed, unless it was an abrupt whole-process termination. The most common cases are:

  • A return within the block
  • An exception being thrown (and not caught) within the block
  • Reaching the end of the block naturally

Basically a using statement is mostly syntactic sugar for a try/finally block - and finally has all the same properties.

EDIT: From section 8.13 of the C# 4 specification:

A using statement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource.

The finally statement is described in section 8.10 of the specification:

The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution; as a result of executing a break, continue, goto or return statement; or as a result of propagating an exception out of the try statement.




回答2:


Yes.

using is syntactic sugar for a try/finally block:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block;

In the documentation on the finally block:

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

So, the using gets translated to try/finally, with .Dispose() in the finally part, ensuring that it is always executed no matter what happens in the try/catch.




回答3:


Yes, using is a compiler feature, which expands to

try {
  ...
  return ...;
}
finally {
  foo.Dispose();
}



回答4:


As far as I know the using block will dispose of the object as soon as it exits scope.

Eg, when true is returned, the next statement is outside of scope so the variable will be disposed.




回答5:


I think as soon as the control will go out of {} dispose will be called so in short Yes




回答6:


One point not yet mentioned is that while a "return" within a "using" block will call Dispose on the controlled variable, a "yield return" from within a "using" block within an iterator will not Dispose the controlled variable unless the IEnumerator associated with the iterator is Disposed.



来源:https://stackoverflow.com/questions/6356307/will-a-idisposable-be-disposed-if-the-using-block-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!