Re: Is this pattern OK?
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Fri, 18 Jan 2008 12:08:14 -0800
On Fri, 18 Jan 2008 11:50:43 -0800, richard.markiewicz@xxxxxxxxxxxx <richard.markiewicz@xxxxxxxxxxxx> wrote:
So what you are saying is, if my original snippet looked like this:
finally
{
objSearchResults.Dispose(); //The troublesome line is now first in the
finally block
objSearchADAM.Dispose();
objADAM.Dispose();
}
That the second and third dispose statements would not be executed
after the first one threw an exception?
Yes. That said, you should of course not have your own code have bugs that throw exceptions, and IMHO the Dispose() method should never throw an exception. But the "using" statement provides the "belts and suspenders" to ensure that even if those rules are violated, things get cleaned up.
Do you know what Using{} does behind the scenes? Does it create a
try{} finally{} on the objects I "use"?
Yes. The "using" statement is essentially equivalent to:
IDisposable obj = // whatever your variable is;
try
{
// code in the using block
}
finally
{
obj.Dispose();
}
Nested "using" statements nest the whole thing:
IDisposable obj1 = ...;
try
{
IDisposeable obj2 = ...;
try
{
// code in the using block
}
finally
{
obj2.Dispose();
}
}
finally
{
obj1.Dispose();
}
Thus even if an inner call to Dispose() throws an exception, the outer ones still get executed.
Note also that the "using" statement essentially generates a private variable that it uses for the call to Dispose(). It doesn't matter what you do to the actual declared variable in your own code, the "using" statement will always call Dispose() on the original reference.
Pete
.
- Follow-Ups:
- Re: Is this pattern OK?
- From: Jon Skeet [C# MVP]
- Re: Is this pattern OK?
- From: richard.markiewicz@xxxxxxxxxxxx
- Re: Is this pattern OK?
- References:
- Is this pattern OK?
- From: richard.markiewicz@xxxxxxxxxxxx
- Re: Is this pattern OK?
- From: Ben Voigt [C++ MVP]
- Re: Is this pattern OK?
- From: Jon Skeet [C# MVP]
- Re: Is this pattern OK?
- From: richard.markiewicz@xxxxxxxxxxxx
- Is this pattern OK?
- Prev by Date: Re: General question to other developers...
- Next by Date: Re: Telnet Clear Screen?
- Previous by thread: Re: Is this pattern OK?
- Next by thread: Re: Is this pattern OK?
- Index(es):
Relevant Pages
|