Search code examples
c#commarshalling

ReportAvOnComRelease Error with Marshal.Release()


I have seen similar errors here but can't quite determine what's causing it.

I have an IntPtr which is referencing a GetForegroundWindow() object :

IntPtr ptr = GetForegroundWindow();

This GetForegroundWindow() method is as such :

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

This in turn is used to establish the GetExecutablePath() method:

string name = GetExecutablePath(ptr);

After such time I am calling the notorious Marshal.Release()

Marshal.Release(ptr);

Upon which time I get the following error :

Managed Debugging Assistant 'ReportAvOnComRelease' has detected

Some more information includes :

Additional information: An exception was caught but handled while releasing a COM interface pointer through Marshal.Release, Marshal.ReleaseComObject or implicitly after the corresponding RuntimeCallableWrapper was garbage collected. This is the result of a user refcount error or other problem with a COM object's Release. Make sure refcounts are managed properly. While these types of exceptions are caught by the CLR, they can still lead to corruption and data loss so if possible the issue causing the exception should be addressed

To me this would suggest that there is a very high probability of a Memory leak or pointer corruption.

I can't seem to establish the cause though as you can see from the extremely simple and straightforward use-case.

Any suggestions on how to debug and / resolve this issue ?


Solution

  • You are fuzzy on the concept of COM. You are not using any, this is plain pinvoke. The MDA correctly tells you that what you are doing does not make any sense.

    Marshal.Release() is only intended to decrement the reference count on a COM interface pointer. Not a window handle. The lifetime of a window is controlled by the user or the thread that created the window. So you must not try to "release" the return value of GetForegroundWindow().

    Simply delete Marshal.Release().