How to remove an unmanaged resource manually?

I am using some kind of unmanaged code, for example -

 [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 / clear this external static object when calling Dispose?

+3
source share
3 answers

What you consider to be an “external static object” is not an object at all, it is just a set of instructions for the compiler / runtime on how to find a function in a DLL.

As Sander says, there is nothing to clean.

+5
source

You do not have pens for unmanaged resources here. Nothing to clean.

+3
source

It depends if you can get a pointer as an example

[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);

public void DoSomething() {
    IntPtr token = IntPtr.Zero;
    WindowsImpersonationContext user = null;
    try {
        bool loggedin = LogonUser((string)parameters[1], (string)parameters[2], (string)parameters[3], LogonSessionType.Interactive, LogonProvider.Default, out token);
        if (loggedin) {
            WindowsIdentity id = new WindowsIdentity(token);
            user = id.Impersonate();
        }
    } catch (Exception ex) {

    } finally {
        if (user != null) {
            user.Undo();
        }
        if (token != IntPtr.Zero) {
            CloseHandle(token);
        }
    }
}
+2
source

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


All Articles