3

I have a statefull legacy COM object. And I need to properly set state and call operation on it.

It works fine until I try do this logic sequentially on the same object (got error because of how this component written). So I need fresh COM object for each iteration.

I get COM object like this:

Activator.CreateInstance(Type.GetTypeFromProgID("MyComType"));

And release objects like this:

public void close()
{
    createdComObjects.Reverse();
    foreach(object item in createdComObjects)
    {
        Marshal.FinalReleaseComObject(item); //also tried ReleaseComObject
    }
}

But this does not work... I get the same COM instance every time and legacy error because of not fresh state.

And one more detail – when I run .exe with one business logic iteration, everything works fine and I can even parallel .exe calls in different consoles without state error.

So questions are:

  1. How can I use Activator.CreateInstance to get a fresh instance on every call? (just like separate .exe invocations do)
  2. How can I fully release instances in order to get fresh ones on next call? (just like exit from .exe does)
Stas Bichenko
  • 13,013
  • 8
  • 45
  • 83
  • Marshal.FinalReleaseComObject() often does not get the job done, the bane of manual memory management. You may well have another interface reference somewhere, not necessarily stored in a named variable. Like obj.foo.bar, the foo reference isn't stored in a variable. Or obj[index] on an indexed property. If you can't hunt it down, pretty tough to find unnamed references, then GC.Collect() might well be able to do it. It knows *everything*. Sure, you are not supposed to use it. Unless you have to – Hans Passant Feb 21 '16 at 14:55
  • i think you should use a manual com activation style for this problem as described here http://stackoverflow.com/questions/26514954/registration-free-com-interop-deactivating-activation-context-in-finalizer-thro. managed environment will not clear objects on the fly as Hans pointed. so try to do it manually. – ivanenok Feb 21 '16 at 15:08

0 Answers0