Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose unmanaged resource manually?

I am using some unmanaged code like-

 [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet() {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }

Any suggestions on how I can dispose/cleanup this extern static object when I call Dispose?

like image 879
Arpit Khandelwal Avatar asked Jan 18 '11 08:01

Arpit Khandelwal


People also ask

Can garbage collector clean unmanaged objects?

Now, it is important to note that the garbage collector cleans and reclaims unused managed objects only. It does not clean unmanaged objects.

Which interface is used to clean up unmanaged resources?

There are different ways to cleanup unmanaged resources: Implement IDisposable interface and Dispose method. 'using' block is also used to clean unmanaged resources.

Which method is overridden to clean up unmanaged resources?

A: Automatic way by Finalizer and GC System. Object declares a virtual method Finalize that is called by the GC before the object's memory is reclaimed by the GC and can be overridden to release unmanaged resources.


2 Answers

The thing you think is an 'extern static object' is not an object at all, it's just a set of instructions to the compiler/runtime about how to find a function in a DLL.

As Sander says, there's nothing to clean up.

like image 167
Will Dean Avatar answered Nov 08 '22 10:11

Will Dean


You do not have any handles to unmanaged resources here. There is nothing to clean up.

like image 41
Sander Avatar answered Nov 08 '22 12:11

Sander