Come smaltire manualmente risorsa non gestita?
-
12-10-2019 - |
Domanda
Sto usando un certo codice non gestito come -
[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);
}
Qualche suggerimento su come posso smaltire / cleanup questo oggetto statico extern quando chiamo Smaltire?
Soluzione
La cosa che pensi è un 'oggetto statico extern' non è un oggetto a tutti, è solo un insieme di istruzioni per il compilatore / runtime su come trovare una funzione in una DLL.
Come Sander dice, non c'è niente da ripulire.
Altri suggerimenti
Non hai nessun maniglie a risorse non gestite qui. Non c'è niente da ripulire.
Dipende se è possibile ottenere un puntatore, come ad esempio
[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);
}
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow