Dispose COM instance obtained via Reflection

O

Oleg Ogurok

Hi all,

I wrote a Windows service that periodically creates a COM instance a calls a
method of it. All of it is done through Reflection because I don't know the
names of the COM object/method at compile time.

I notice that when I build a newer version of a COM dll, when I try to copy
it to the destination dir, I get an error "File is in use by another
process." I know for sure that it's my Windows Service using it because once
I stop it, I can install the new COM dll.

What do I have to do in order to dispose the COM instance?


Here's the code of my launching method.


public void Launch()
{
Type type = Type.GetTypeFromProgID(programName);
if (type == null)
{ throw new LaunchException("Can't find program " + programName + ",
perhaps it's not registered");
}

try
{
object instance = Activator.CreateInstance(type);
type.InvokeMember(methodName,
BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.InvokeMethod,
null, instance, arguments);
//TODO COM object remains in memory, need to dispose.
}
catch (Exception e)
{
throw new LaunchException("Error running COM method " + methodName + "
in class " + programName, e);
}
catch
{
string error = "Error running COM method " + methodName + " in class " +
programName;
throw new LaunchException(error);
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Oleg,

When you are done, you should pass the instance of the COM object to the
static ReleaseComObject method on on the Marshal class. This should release
the reference. However, the library should still be loaded in memory, so
you will probably have to shut the service down anyways.

In order to get around this, you might want to call the
CoFreeUnusedLibraries function through the P/Invoke layer (I believe this
will unload the COM dll assuming it is not in use anymore).

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top