Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

I'm calling Marshal.ReleaseComObject but com objects are still leaking. How to properly release MODI.Document??

23 views
Skip to first unread message

DR

unread,
Feb 5, 2008, 5:22:31 PM2/5/08
to
I'm calling Marshal.ReleaseComObject but com objects are still leaking. How
to properly release MODI.Document??

private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000000; i++)
{
MODI.Document miDoc = new MODI.Document();
miDoc.Create("a.gif");
miDoc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image tifImg = (MODI.Image)miDoc.Images[0];
string recSTring = tifImg.Layout.Text;
miDoc.Images.Remove(tifImg);
miDoc.Close(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(tifImg);
System.Runtime.InteropServices.Marshal.ReleaseComObject(miDoc);
}
}


Scott M.

unread,
Feb 5, 2008, 6:16:01 PM2/5/08
to
See answer in Framework NG.


"DR" <softwareen...@yahoo.com> wrote in message
news:exOz1WEa...@TK2MSFTNGP03.phx.gbl...

Nicholas Paldino [.NET/C# MVP]

unread,
Feb 5, 2008, 8:23:06 PM2/5/08
to
I believe I already answered this in the previous answer to your post.

Assuming that miDoc is a COM object, you need to release the COM objects
pointed to by the following variables:

miDoc
miDoc.Images
tifImg
tifImg.Layout

I usually create a structure of some kind which will call
ReleaseComObject for COM objects:

public struct ComReference<T> : IDisposable where T : class
{
public T Value { get; private set; }

public ComReference(T value)
{
Value = value;
}

public void Dispose()
{
if (Value != null)
{
Marshal.ReleaseComObject(Value);
}
}
}

Then, you would change your code like this:

private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000000; i++)
{

using (ComReference<MODI.Document> miDoc = new
ComReference<MODI.Document>(new MODI.Document()))
{


miDoc.Create("a.gif");
miDoc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

// Get the images.
using (ComReference<MODI.Images> tifImgs = new
ComReference<MODI.Images>(miDoc.Images))
using (ComReference<MODI.Image> tifImg = new
ComReference((MODI.Image) tifImgs[0]))
{
string recSTring = tifImg.Layout.Text;

tifImgs.Remove(tifImg);

miDoc.Close(false);
}
}
}
}

MODI.Images is the type that is exposed by the Images property on the
miDoc reference.

Basically, what the above does is guarantee that all the references are
released properly when you are done using them (and in the face of an
exception as well). You aren't accounting for the references that are
exposed when you call the Images property on the miDoc reference.


--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com

"DR" <softwareen...@yahoo.com> wrote in message
news:exOz1WEa...@TK2MSFTNGP03.phx.gbl...

0 new messages