Search code examples
c#processcomcom+

Best way to kill an out of process dll ('dllhost.exe' 'COM Surrogate') when an App exits?


I am using the 'DllSurrogate' method to allow a 64-bit C# exe to talk to a 32-bit C# dll. The method is described in Out-of-process COM Server Demo.

When the App runs an extra process called 'dllhost.exe *32' automatically shows up in Task Manager, with the description 'COM Surrogate'. This is the link between the App and the 32-bit dll.

The problem I have is that this process is not killed when the App exits. Can someone suggest the recommended way of dealing with this?

I could find the process and kill it as my App closes, but I would need to make sure:

  • It is my 'COM Surrogate', not one belonging to another App.
  • It is not being used by another running instance of my App.

Is there a more direct link between my App and this process that I can check?


Solution

  • A COM surrogate, which refuses to terminate, usually indicates outstanding references to a CoClass or resources, which haven't been released yet. You can enforce the release by resorting to ReleaseComObject or FinalReleaseComObject. However, when using this approach, you should be aware of the associated risks, as described here.

    If you're still seeing no other way than terminating the COM surrogate manually, you'll need to enumerate all dllhost.exe processes on your machine. Extract the command line of each candidate and look for the /ProcessId argument. If it matches the GUID of your CoClass, then you have found the match.