Re: Is this pattern OK?



On Jan 18, 2:32 pm, Jon Skeet [C# MVP] <sk...@xxxxxxxxx> wrote:
Ben Voigt [C++ MVP] <r...@xxxxxxxxxxxxx> wrote:

<snip>

What you ought to do instead is convert try / finally { Dispose(); } into
using blocks, which automatically handle the null case.

They also cope with the possibility of Dispose calls throwing
exceptions - with a single finally block, if an early Dispose call
fails, the rest won't get executed.

--
Jon Skeet - <sk...@xxxxxxxxx>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
World class .NET training in the UK:http://iterativetraining.co.uk

Thank you Jon.

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?

Do you know what Using{} does behind the scenes? Does it create a
try{} finally{} on the objects I "use"?

We had a lot of problems with System.DirectoryServices in .NET 1.1
where objects weren't disposed properly, and I'm keen not to go down
that route again. So it would be good to know that my revised pattern
is not subject to the same problem.

Many thanks, Richard
.



Relevant Pages

  • Re: Paradigm for multiple IDisposables
    ... you and call IDisposable in the face of exceptions. ... IDisposable on MultiDispose, you have to wrap the call to Dispose on each ... a list of IDisposables inside the using statement, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Whats finally keyword good for?
    ... I write code for BLL and DAL, and I don't write the kind of code you are talking about that needs to be looking at a bunch of exceptions. ... databse server like Oracle and it blows with the connection open. ... One has a SQL command abort inside the USING with a open connection and no *close* and *dispose* occurs, and the connection is left open. ... // Open resources required for the processing ...
    (microsoft.public.dotnet.languages.csharp)
  • property access after Dispose()
    ... exceptions on all attempts to access once disposed. ... isn't absolutely necessary to dispose) and i want the ... >I've seen classes in the .NET class library throw ... >exceptions when a method is called on a disposed method, ...
    (microsoft.public.dotnet.framework.aspnet.security)
  • Re: Retrieve thrown exception in using (disposable) cleanup
    ... Thanks for the suggestion. ... I hoped it might be possible to detect thrown exceptions in the same way ... Can you save ErrorException in a field until Dispose ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Is this pattern OK?
    ... They also cope with the possibility of Dispose calls throwing ... exceptions - with a single finally block, ...
    (microsoft.public.dotnet.languages.csharp)