Consider the following code:
namespace DisposeTest
{
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Calling Test");
Test();
Console.WriteLine("Call to Test done");
}
static void Test()
{
DisposeImplementation di = new DisposeImplementation();
}
}
internal class DisposeImplementation : IDisposable
{
~DisposeImplementation()
{
Console.WriteLine("~ in DisposeImplementation instance called");
}
public void Dispose()
{
Console.WriteLine("Dispose in DisposeImplementation instance called");
}
}
}
The Dispose just never get's called, even if I put a wait loop after the Test();
invocation. So that quite sucks. I want to write a class that is straightforward and very easy to use, to make sure that every possible resource is cleaned up. I don't want to put that responsibilty to the user of my class.
Possible solution: use using
, or call Dispose myself(basicly the same). Can I force the user to use a using? Or can I force the dispose to be called?
Calling GC.Collect();
after Test();
doesn't work either.
Putting di
to null
doesn't invoke Dispose either. The Deconstructor DOES work, so the object get's deconstructed when it exits Test()
Ok guys, it's clear now!
Thank you all for your answers! I will add a warning in the comment!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…