How to dispose unmanaged resource manually?
Asked Answered
L

3

7

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?

Lillalillard answered 18/1, 2011 at 8:28 Comment(0)
E
7

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.

Expose answered 18/1, 2011 at 8:52 Comment(0)
W
4

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

Woodborer answered 18/1, 2011 at 8:47 Comment(0)
C
3

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);
        }
    }
}
Carline answered 18/1, 2011 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.