I obtain an IStorage
object from OLE32's StgCreateStorageEx
function. Here is its declaration:
Imports Microsoft.VisualStudio.OLE.Interop
<System.Runtime.InteropServices.DllImport("ole32.dll",
SetLastError:=True, CharSet:=CharSet.Unicode)>
Private Shared Function StgCreateStorageEx(
<MarshalAs(UnmanagedType.LPWStr)>
ByVal pwcsName As String,
ByVal grfMode As UInt32,
ByVal stgFmt As UInt32,
ByVal grfAttrs As UInt32,
ByRef pStgOptions As SStgOptions,
ByVal pSecurityDescriptor As IntPtr,
<[In]()> ByRef riid As Guid,
<[Out]()> ByRef ppObjectOpen As IStorage) As Int32
End Function
The caller sets the flags and the structure member, then obtains a new IStorage
object in an oStorage As IStorage
object. So far all is well.
The documentation kindly reminds us:
An application must release its IStorage pointers when it is done with
the storage object to deallocate memory used.
Since the object was created by COM and consumes memory, and since we all don't like memory leaks, the standard thing to do would be to properly implement IDisposable
and dispose of the caller's oStorage
object, via the Marshal.ReleaseComObject(oStorage)
method. But...
I happened to come across this document Marshal.ReleaseComObject Considered Dangerous, by the Visual Studio developers. Only that...
I am not sure if I understand the causes thoroughly. However, it seems to be a clear advice to stay away from ReleaseComObject
altogether. But...
The document stems from 2010. Is this still the proper advice, more than a decade later? And...
How would I otherwise prevent memory leaks?
question from:
https://stackoverflow.com/questions/65847046/do-i-need-to-clean-up-unmanaged-code-after-obtaining-an-istorage-object-from-ole 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…