Knowledge base KB0203

How to use Office Automation from managed code (C#, Visual Basic, .NET)

Problem

Office uses COM to expose automation objects. In managed code, as used by C# and Visual Basic, the COM objects are wrapped in Runtime Callable Wrappers (RCWs). Without any special action by the programmer, COM objects wrapped in RCWs are released only on Garbage Collection, which in the absence of memory pressure may be never.

Solution

To deterministically release COM objects, release all objects you receive from Office with System.Runtime.InteropServices.Marshal.ReleaseComObject after you are done using them.

Note

  • Do not use System.Runtime.InteropServices.Marshal.FinalReleaseComObject because it will release the COM object even if other managed add-ins are still using it.

  • Do not access an object through another one, e.g.:

    // C#
    // Wrong
    PowerPoint.View view = Application.ActiveWindow.View;
    ' Visual Basic
    ' Wrong
    Dim view As PowerPoint.View = Application.ActiveWindow.View

    In this case, ActiveWindow creates a temporary PowerPoint.DocumentWindow, which is not released.

    Instead, assign it to a variable and release it:

    // C#
    PowerPoint.DocumentWindow wnd = Application.ActiveWindow;
    PowerPoint.View view = wnd.View;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wnd);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(view);
    ' Visual Basic
    Dim wnd As PowerPoint.DocumentWindow = Application.ActiveWindow
    Dim view As PowerPoint.View = wnd.View
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wnd)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(view)

Share