66

This was a telephone interview question I had: Is there a time when Dispose will not be called on an object whose scope is declared by a using block?

My answer was no - even if an exception happens during the using block, Dispose will still be called.

The interviewer disagreed and said if using is wrapped in a try-catch block then Dispose will not be called by the time you enter the catch block.

This goes contrary to my understanding of the construct, and I haven't been able to find anything that backs up the interviewers point of view. Is he correct or might I have misunderstood the question?

13
  • 10
    The interviewer is wrong; don't take the job! Not least, do you want to work for someone who likes to leave landmines around? Commented Sep 29, 2011 at 9:45
  • 7
    If you have the interviewers email address, email him back and show him the code that demonstrates that the dispose is called. If he's not impressed don't work for him :) Commented Sep 29, 2011 at 9:47
  • 9
    Take the job ! They need you there ! Commented Sep 29, 2011 at 9:58
  • 8
    Perhaps you were interviewed by the same guy Alex Papadimoulis was interviewed by? thedailywtf.com/Articles/My-Tales.aspx Commented Sep 29, 2011 at 14:55
  • 3
    EMP would do it. General power loss could too. Commented Sep 29, 2011 at 19:02

8 Answers 8

58

Four things that will cause Dispose to not be called in a using block:

  1. A power failure on your machine when inside the using block.
  2. Your machine getting melted by an atomic bomb while in the inside of the using block.
  3. Uncatchable exceptions like StackOverflowException, AccessViolationException and possibly others.
  4. Environment.FailFast
Sign up to request clarification or add additional context in comments.

7 Comments

Listed in order of probability ;)
Should we mark every using block with a 'Radioactive Hazard' sign because of #2? Please advice!!!!1111 en.wikipedia.org/wiki/File:Radioactive.svg
Stackoverflow exception - great example!
4. Environment.Failfast listed below. msdn.microsoft.com/en-us/library/ms131100.aspx
Perhaps even ExecutionEngineException will break the finally block, but it's quite complex to test :-)
|
53
void Main() { try { using(var d = new MyDisposable()) { throw new Exception("Hello"); } } catch { "Exception caught.".Dump(); } } class MyDisposable : IDisposable { public void Dispose() { "Disposed".Dump(); } } 

This produced :

Disposed Exception caught 

So I agree with you and not with the smarty interviewer...

10 Comments

Why is this the accepted answer? This isn't how science works, you don't just pick a specific, tailor-made example and declare your theory perfect... In case you're wondering, you are in fact completely wrong, it is possible for Dispose not to get called.
@blindy: Wouaw, that really pissed you off, sorry. Are you hiring ;-)
@Blindy "The interviewer disagreed and said if using is wrapped in a try catch block then Dispose will not be called by the time you enter the catch block." I think the answer is a pretty good counterexample to the interviewer's "theory".
Forgive me but what is .Dump() on the strings?
@Will, Øyvind did that for me, why retype it? And I never tried to prove it is possible for Dispose not to get called, VdesmedT did, and he tried it by choosing a working example. My point, I believe, stands.
|
25

Bizarrely I read about a circumstance where Dispose won't get called in a using block just this morning. Checkout this blog on MSDN. It's around using Dispose with IEnumerable and the yield keyword, when you don't iterate the entire collection.

Unfortunately this doesn't deal with the exception case, honestly I'm not sure about that one. I would have expected it to be done but maybe it's worth checking with a quick bit of code?

1 Comment

The behavior described in the post is very logical. Dispose in an iterator (yield) method will not get called if the consumer of the returned iterator does not call Dispose on that IEnumerator. Or in other words: "Dispose won't get called in cases you don't call Dispose", which is of course trivial. The solutions: wrap the usage of an IEnumerator in a using block, or iterate it using the C# foreach statement.
21

The other answers about power failure, Environment.FailFast(), iterators or cheating by using something that is null are all interesting. But I find it curious that nobody mentioned what I think is the most common situation when Dispose() won't be called even in the presence of using: when the expression inside using throws an exception.

Of course, this is logical: the expression in using threw an exception, so the assignment didn't take place and there is nothing we could call Dispose() on. But the disposable object can already exist, although it can be in half initialized state. And even in this state it can already hold some unmanaged resources. This is another reason why correctly implementing the disposable pattern is important.

Example of the problematic code:

using (var f = new Foo()) { // something } … class Foo : IDisposable { UnmanagedResource m_resource; public Foo() { // obtain m_resource throw new Exception(); } public void Dispose() { // release m_resource } } 

Here, it looks like Foo releases m_resource correctly and we are using using correctly too. But the Dispose() on Foo is never called, because of the exception. The fix in this case is to use finalizer and release the resource there too.

7 Comments

+1 Very nice catch. Actually, I would say the "fix" is to not allowcate unmanaged resources in the ctor at all. All access to such resources should be done using lazy loading.
First time I learned an argument for not initializing an object in constructor. Everything I know about RAII is wrong :(
@HemalPandya, I think RAII is much more important in C++, because it doesn't have a garbage collector or using. But I don't think this is an argument against initialization in constructor. It's more an argument for properly implementing finalizer, if you need it.
There is no need to release managed resources in finalizer, because they will be (or, possibly, already have been) GCed. And if they, in turn, own some unmanaged resources, they should take care of them in their finalizers.
This answer is especially interesting because it may mean that the interviewer is somewhat right. I disagree on the fix, I would prefer that if the constructor can throw that resources should be released in a catch block in the constructor and the exception rethrown, because there is no guarantee on if/when your finalizer is going to be called.
|
19

The using block gets turned by the compiler into a try/finally block of its own, within the existing try block.

For example:

try { using (MemoryStream ms = new MemoryStream()) throw new Exception(); } catch (Exception) { throw; } 

becomes

.try { IL_0000: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor() IL_0005: stloc.0 .try { IL_0006: newobj instance void [mscorlib]System.Exception::.ctor() IL_000b: throw } // end .try finally { IL_000c: ldloc.0 IL_000d: brfalse.s IL_0015 IL_000f: ldloc.0 IL_0010: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0015: endfinally } // end handler } // end .try catch [mscorlib]System.Exception { IL_0016: pop IL_0017: rethrow } // end handler 

The compiler won't rearrange things. So it happens like this:

  1. Exception is thrown in, or propagates to, the using block's try part
  2. Control leaves the using block's try part, and enters its finally part
  3. Object is disposed by the code in the finally block
  4. Control leaves the finally block, and the exception propagates out to the outer try
  5. Control leaves the outer try and goes into the exception handler

Point being, the inner finally block always runs before the outer catch, because the exception doesn't propagate til the finally block finishes.

The only normal case where this won't happen, is in a generator (excuse me, "iterator"). An iterator gets turned into a semi-complicated state machine, and finally blocks are not guaranteed to run if it becomes unreachable after a yield return (but before it has been disposed).

2 Comments

The finally happens after control leaves the try block.
@Eric: I actually did mean before, as i was talking about the outer try rather than the one that using generated. But it gets a bit confusing when you're talking about both at once. Hopefully clarified it a bit.
13
using (var d = new SomeDisposable()) { Environment.FailFast("no dispose"); } 

1 Comment

Would be nice if you had more information included: msdn.microsoft.com/en-us/library/ms131100.aspx
5

Yes there is a case when dispose won't be called... you are over thinking it. The case is when the variable in the using block is null

class foo { public static IDisposable factory() { return null; } } using (var disp = foo.factory()) { //do some stuff } 

will not throw an exception but would if dispose was called in every case. The specific case that your interviewer mentioned is wrong though.

Comments

0

The interviewer is partially right. Dispose may not correctly clean up the underlying object on a case-by-case basis.

WCF for example has a few known issues if an exception is thrown while in a using block. Your interviewer was probably thinking of this.

Here is an article from MSDN on how to avoid issues with the using block with WCF. Here is Microsoft's official workaround, although I now think that a combination of that answer and this one is the most elegant approach.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.