When is a destructor called for C # classes in ASP.NET?

Let's say I have my own C # class defined as such:

public class MyClass { public MyClass() { //Do the work } ~MyClass() { //Destructor } } 

And then I instantiate my class from an ASP.NET project, as such:

 if(true) { MyClass c = new MyClass(); //Do some work with 'c' //Shouldn't destructor for 'c' be called here? } //Continue on 

I expected the destructor to be called at the end of the if scope, but it never gets called. What am I missing?

+6
source share
3 answers

Equivalent to a C ++ destructor, this is IDisposable and the Dispose() method, which is often used in the using block.

See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

What you call a destructor is better known as Finalizer .

Here you can use IDisposable. Note that Dispose() not called automatically; the best thing you can do is use using , which will call the Dispose() call, even if there is an exception in the using block before it reaches the end.

 public class MyClass: IDisposable { public MyClass() { //Do the work } public void Dispose() { // Clean stuff up. } } 

Then you can use it as follows:

 using (MyClass c = new MyClass()) { // Do some work with 'C' // Even if there is an exception, c.Dispose() will be called before // the 'using' block is exited. } 

You can call .Dispose() explicitly if you need to. The only using point is to automate the call to .Dispose() when execution for some reason leaves the using block.

See here for more information: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx

Basically, the using block above is equivalent:

 MyClass c = new MyClass(); try { // Do some work with 'C' } finally { if (c != null) ((IDisposable)c).Dispose(); } 
+6
source

It is not possible to control time or make an assumption when the actual object destructor will be called. All this to the Garbage Collector .

The only thing you can be sure in this case is that you are currently leaving this area, the c object becomes inaccessible (I assume that there are no global references to this instance inside the region), so the c instance must be identified and deleted from using the Garbage Collector when the time comes.

+4
source

It depends on the garbage collector regarding when the object is freed. However, you can force an object to be released by calling Finalize . or GC.Collect , which will force the garbage collector to take action.

+2
source

Source: https://habr.com/ru/post/947971/


All Articles