Reputation: 183
I have this test code. Why is the dispose method not called when an exception is raised inside using statement? According to the documentation it should be called.
using System;
using System.IO;
using System.Text;
namespace UsingTest {
class Program {
public class MyClass : IDisposable
{
private bool disposed = false;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
using (var f = new FileStream("log.txt", FileMode.Create)) {
var msg = "MyClass disposed";
f.Write(Encoding.UTF8.GetBytes(msg), 0, Encoding.UTF8.GetByteCount(msg));
}
}
disposed = true;
}
}
~MyClass() {
Dispose(false);
}
}
static void Main(string[] args) {
using (var c = new MyClass()) {
Console.WriteLine("some work");
throw new Exception("Exception");
Console.WriteLine("Hello World!");
}
}
}
}
Thanks.
Upvotes: 0
Views: 2870
Reputation: 38499
static void Main(string[] args) {
using (var c = new MyClass()) {
Console.WriteLine("some work");
throw new Exception("Exception");
Console.WriteLine("Hello World!");
}
}
This is creating a new instance of MyClass
While it's instantiated, it writes to the console. Then throws an exception.
On exception, the debugger steps in, and tries to help you out debugging the code.
The debugger in Visual Studio will keep running your code long enough to do that - debug it.
if you will run it from Visual Studio with debugger - it will not be called
The method (Dispose) is being called after the debugger stops running / listening to your code.
Your breakpoints in Dispose
won't be hit, since the debugger is no longer there.
The code isn't being run, since the runtime has exited (by order of Visual Studio determining you're now finished)
If you run it without debugging (ctrl+f5) you will see the file created too.
Try putting a System.Diagnostics.Debugger.Launch();
inside your Dispose method, like this:
public void Dispose(bool disposing) {
System.Diagnostics.Debugger.Launch();
//etc
}
This will attach the debugger at that point in time.
Upvotes: 5