0

When using the following code:

Dim modiDocument As New MODI.Document
modiDocument.Create(TifFile)
modiDocument.Close(False)

Then the TifFile isn't locked and I can do things like e.g. delete it (IO.File.Delete).

However when I enumerate the Images then the file will be locked:

Dim modiDocument As New MODI.Document
modiDocument.Create(TifFile)
For Each modiImage In modiDocument.Images
  'Doesn't matter if I enter code here or not.
Next
modiDocument.Close(False)

Now the file will be locked.

I tried everything (I think) to solve this, like:

Dim modiDocument As New MODI.Document
modiDocument.Create(TifFile)
For Each modiImage In modiDocument.Images
  Marshal.ReleaseComObject(modiImage)
Next
Marshal.ReleaseComObject(modiImage)
modiDocument.Close(False)
Marshal.ReleaseComObject(modiDocument)

Yes, I also tried FinalReleaseComObject.

So far, no luck.

How can I solve this?

NB: The example here are in VB. I also know C#, so it doesn't matter in which language you provide code examples.

  • `FinalReleaseComObject` calls `ReleaseComObject` in a loop til it's released, it maybe more times than 3 times. So you should try `FinalReleaseComObject` – OneFineDay Nov 20 '14 at 16:06
  • I tried that without result –  Nov 20 '14 at 17:47
  • There is an enumerator object that you cannot see, probably IEnumVariant. This is in general why it is such a bad idea to try to implement manual memory management, the syntax sugar in VB.NET and C# give you far too much rope to hang yourself. [Read this](http://stackoverflow.com/a/25135685/17034). – Hans Passant Nov 24 '14 at 09:57
  • related: http://stackoverflow.com/questions/2191489/releasing-temporary-com-objects – Henrik Nov 24 '14 at 10:07

1 Answers1

1

You need to release every COM object you instantiate, and it's very easy to miss one. E.g. you have missed modiDocument.Images.

The following may help:

modiDocument.Create(TifFile)
var images = modiDocument.Images
For Each modiImage In images
    ...
Next
...
Marshal.ReleaseComObject(images)

If you add code in the For Each loop that instantiates additional COM objects, they'll need to be cleaned up too.

Joe
  • 122,218
  • 32
  • 205
  • 338