Arpit Khandelwal
Arpit Khandelwal

Reputation: 1803

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?

Upvotes: 7

Views: 3981

Answers (3)

djeeg
djeeg

Reputation: 6765

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);
        }
    }
}

Upvotes: 3

Will Dean
Will Dean

Reputation: 39530

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.

Upvotes: 7

Sander
Sander

Reputation: 26374

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

Upvotes: 4

Related Questions