Setting to null is definitely not enough. In this case, additionally you have to force the garbage collector to swipe the heap as soon as possible. You do this correctly with calls to GC.Collect()
and GC.WaitForPendingFinalizers()
. Calling twice is safe, end ensures that cycles are definitely cleaned up too.
But I'd recommend using System.Runtime.InteropServices.Marshal.ReleaseComObject
to release an Outlook object when you have finished using it. Then set a variable to Nothing
in Visual Basic (null
in C#) to release the reference to the object. This is particularly important if your add-in attempts to enumerate more than 256 Outlook items in a collection that is stored on a Microsoft Exchange Server (this number was increased in latest versions). If you do not release these objects in a timely manner, you can reach the limit imposed by Exchange on the maximum number of items opened at any one time.
The ReleaseComObject
method is used to explicitly control the lifetime of a COM object used from managed code. You should use this method to free the underlying COM object that holds references to resources in a timely manner or when objects must be freed in a specific order.
Every time a COM interface pointer enters the common language runtime (CLR), it is wrapped in an RCW.
The RCW has a reference count that is incremented every time a COM interface pointer is mapped to it. The ReleaseComObject
method decrements the reference count of an RCW. When the reference count reaches zero, the runtime releases all its references on the unmanaged COM object, and throws a System.NullReferenceException
if you attempt to use the object further. If the same COM interface is passed more than one time from unmanaged to managed code, the reference count on the wrapper is incremented every time, and calling ReleaseComObject returns the number of remaining references.
The ReleaseComObject
method enables you to force an RCW reference count release so that it occurs precisely when you want it to. However, improper use of ReleaseComObject
may cause your application to fail, or may cause an access violation.