C
Curious
We all know that in .NET, we don't need to worry about memory leak
becaseu GC does a nice job to collect it.
The only time we need to worry about memory leak is when we use
unmanaged resources, such as COM-based objects written in C++, for an
instance. Therefore, I've created the following sample code below to
illustrate the step necessary in disposing unmanaged resources.
I believe that to dispose unmanaged resources, we'll need to call the
Destructor of the COM object. However, I don't know what's the right
syntax. I'm looking for advice and input on the piece of code below.
Thanks!
using System;
using System.Runtime.InteropServices;
namespace iopmb
{
[DllImport("user32.dll", EntryPoint="MessageBoxW",
CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool COMDbConnection (string connectionString,
bool useTrustedConnection, string, userName, string password);
COMDbConnection myConnection = new
COMDbConnection("Provider=sqloledb;Data Source=DataWarehouse;Initial
Catalog=Pace;", true, "sa", "password") ;
try
{
// do something with myConnection
}
catch
{
finally
{
myConnection.Dispose() ;
}
}
class COMDbConnection
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Call distructor of the COM object. I know this is not right to
clean memory this way.
// But if anyone points out the right way, I'd appreciate it!
this.~COMDbConnection();
}
// This should be skipped
//base.Dispose(disposing);
}
}
becaseu GC does a nice job to collect it.
The only time we need to worry about memory leak is when we use
unmanaged resources, such as COM-based objects written in C++, for an
instance. Therefore, I've created the following sample code below to
illustrate the step necessary in disposing unmanaged resources.
I believe that to dispose unmanaged resources, we'll need to call the
Destructor of the COM object. However, I don't know what's the right
syntax. I'm looking for advice and input on the piece of code below.
Thanks!
using System;
using System.Runtime.InteropServices;
namespace iopmb
{
[DllImport("user32.dll", EntryPoint="MessageBoxW",
CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool COMDbConnection (string connectionString,
bool useTrustedConnection, string, userName, string password);
COMDbConnection myConnection = new
COMDbConnection("Provider=sqloledb;Data Source=DataWarehouse;Initial
Catalog=Pace;", true, "sa", "password") ;
try
{
// do something with myConnection
}
catch
{
finally
{
myConnection.Dispose() ;
}
}
class COMDbConnection
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Call distructor of the COM object. I know this is not right to
clean memory this way.
// But if anyone points out the right way, I'd appreciate it!
this.~COMDbConnection();
}
// This should be skipped
//base.Dispose(disposing);
}
}