Can code run when an object goes out of scope in .Net?

Is there a way to "automatically" run the completion / destructor code as soon as the variable loses its scope in the .NET language? It seems to me that since the garbage collector runs indefinitely, the destructor code does not run as soon as the variable loses scope. I understand that I can inherit from IDisposable and explicitly call Dispose on my object, but I was hoping there might be more connection problems, similar to how non.Net C ++ handles object destruction.

Desired Behavior (C #):

public class A {
    ~A { [some code I would like to run] }
}

public void SomeFreeFunction() {
    SomeFreeSubFunction();
    // At this point, I would like my destructor code to have already run.
}

public void SomeFreeSubFunction() {
    A myA = new A();
}

Less desirable:

public class A : IDisposable {
    [ destructor code, Dispose method, etc. etc.]
}

public void SomeFreeFunction() {
    SomeFreeSubFunction();
}

public void SomeFreeSubFunction() {
    A myA = new A();
    try {
        ...
    }
    finally {
        myA.Dispose();
    }
}
+5
source share
3 answers

using , :

using (MyClass o = new MyClass()) 
{
 ...
}

Dispose() , . IDisposable.

, . .

+9

using , IDisposable, .

:

using(FileStream stream = new FileStream("string", FileMode.Open))
{
    // Some code
}

:

FileStream stream = new FileStream("string", FileMode.Open);
try
{
    // Some code
}
finally
{
    stream.Dispose();
}
+4

Unfortunately no.

Your best option is to implement IDisposable with an IDisposable pattern .

+3
source

All Articles