Dispose Unmanaged resources
- From: Curious <fir5tsight@xxxxxxxxx>
- Date: Mon, 17 Mar 2008 08:11:44 -0700 (PDT)
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);
}
}
.
- Follow-Ups:
- Re: Dispose Unmanaged resources
- From: Duy Lam
- Re: Dispose Unmanaged resources
- From: Sergey Zyuzin
- Re: Dispose Unmanaged resources
- Prev by Date: Car-Sharing Offered - ICC Birmingham MS UK Product Launch, 19th March
- Next by Date: IE 7 error
- Previous by thread: Car-Sharing Offered - ICC Birmingham MS UK Product Launch, 19th March
- Next by thread: Re: Dispose Unmanaged resources
- Index(es):
Relevant Pages
|