Where is the destructor C #

I have a class that spawns another UI thread and does this. I need to interrupt this thread and clean it up when my parent class is destroyed. So how do I know when my parent class is destroyed?

Coming from C ++ my first thought was to put this in a destructor. But C # doesn't really have destructors - only finalizers and utilities, which from what I understand may or may not be called (I guess this is the mood for GC ??).

It's great and easy - if you may or may not want to release your resources.

But where do you put the code that ABSOLUTELY POSITIVE SHOULD BE EXECUTED whenever the object is destroyed?

+3


source to share


4 answers


You put it in Dispose

(implement the interface IDisposable

) and then make sure to be Dispose

called when the object is no longer required. There's a language construct out there that does exactly that:

using (var foo = new Foo())
{
    // Do something with foo.
}

      

foo.Dispose

will be called at the end of the block using

. This is equivalent to:

{
    var foo = new Foo();
    try
    {
        // Do something with foo.
    }
    finally
    {
        foo.Dispose();
    }
}

      

Note that notDispose

automatically when the object leaves the area; you need to do it yourself using either a block or explicitly calling it.using



However, you must provide a finalizer in Foo

that calls Dispose

, so that if the object isn't disposed of before the GC gets to it, you won't be left with unreleased resources:

~Foo()
{
    Dispose();
}

      


The idea behind the template IDisposable

is that it tells you unambiguously when a class needs disposal. Here's an article that describes how to properly implement it (accounting for possible descendant classes).

+5


source


There is no way to guarantee that something "ABSOLUTELY POSITIVE [WILL] FULFILL" when the object is destroyed (try pulling the plug on your pc --- no finalizers will be called)



The best you can hope for is a finalizer defined in C # using the C ++ destructor syntax. Though you are better off implementing IDisposable and using a block using{}

.

+3


source


Although this method is not generic, you can define a "destructor" in C # using a symbol ~

, for example:

class Parent
{
    ~Parent()  // destructor
    {
        // cleanup statements...
    }
}

      

Note:

The destructor implicitly calls Finalize on the base object class.

( source )

+1


source


You will create a class Component

and a containing class a Container

.

See: C # - What is a component and how is it commonly used?

The other answers seem to be busy with the "out of scope" use case. But "when is my parent class destroyed"? If the "parent class" is the "containing object" then components are the right tool.

0


source







All Articles