Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a situation in which Dispose won't be called for a 'using' block?

Tags:

c#

using

dispose

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?

like image 596
AdamCrawford Avatar asked Sep 29 '11 09:09

AdamCrawford


People also ask

What happens if Dispose is not called?

Implement a finalizer to free resources when Dispose is not called. By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.

Does Dispose get called automatically?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.

Does Dispose get called after exception?

Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up. You must be looking at the wrong file. "Dispose()" gets written to your temp file.

When to use using block in C#?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.


2 Answers

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
like image 88
Øyvind Bråthen Avatar answered Sep 28 '22 01:09

Øyvind Bråthen


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...

like image 29
VdesmedT Avatar answered Sep 28 '22 01:09

VdesmedT