问题
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?
回答1:
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
var context = new linqAssignmentsDataContext();
try {
return context.Persons.Where(p => p.LastName.Contans("dahl"));
} finally {
if ( context != null ) {
context.Dispose();
}
}
回答2:
From the MSDN documentation:
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 fact, this is how the using statement is translated by the compiler.
So the object is always disposed. Unless you plug out the power cable.
来源:https://stackoverflow.com/questions/2284753/what-happens-when-return-is-called-from-within-a-using-block