Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7686007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T19:22:55+00:00 2026-05-31T19:22:55+00:00

Lets say that I have one component which is doing something with Workbook object

  • 0

Lets say that I have one component which is doing something with Workbook object and somewhere in the middle of that method body I have call to some method of another class.
For example:

public class MainComponent
{

    public void MyMainMethod()
    {
       OtherComponent otherComponent = new OtherComponent();
       Workbook document;
       // some work with workbook object

       // working with document and worksheet objects.
       otherComponent.MethodCall(document);

       // some work with workbook object and it's worksheets.

       foreach(Worksheet sheet in document.Workheets)
         // do something with sheet
    }
}

public class OtherComponent
{
  public void MethodCall(Workbook document)
  {
    string worksheetNames = "";
    foreach(Worksheet sheet in document.Worksheets)
      worksheetNames += sheet.Name;
    Console.WriteLine(worksheetNames);
  }
}

And in that otherComponent.MethodCall(document); I’m using document and I’m iterating through it’s worksheets.

EDIT TO be more concrete on question. Should I call ReleaseCOMObject on document and on Worksheets in otherComponent.MethodCall(document) or not?

I never really had any good explanation on how should I manage this unmanaged code.
I would really appreciate if someone could explain this to me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T19:22:57+00:00Added an answer on May 31, 2026 at 7:22 pm

    You’ll have to release all local objects manually in the scope where you create them. When using Office applications through Automation, don’t rely on the garbage collector to clean up these objects – even if it gets it right, it may take time for it to kick in and you may end up with temporary objects holding references to other objects that you think are already gone.

    This is a somewhat related question with more details that may apply to you if you try to run Excel from your application with Excel being hidden.

    The part that’s definitely relevant to you is this:

    • Wrap every single function that uses Excel in a try..catch block to capture any possible exception.
    • Always explicitly release all Excel objects by calling Marshal.ReleaseComObject() and then setting your variables to null as soon as you don’t need them. Always release these objects in a finally block to make sure that a failed Excel method call won’t result in a dangling COM object.
    • When an error happens, close the Excel instance that you’re using. It’s not likely that you can recover from Excel-related errors and the longer you keep the instance, the longer it uses resources.
    • When you quit Excel, make sure that you guard that code against recursive calls – if your exception handlers try to shut down Excel while your code is already in the process of shutting down Excel, you’ll end up with a dead Excel instance.
    • Call GC.Collect() and GC.WaitForPendingFinalizers() right after calling the Application.Quit() method to make sure that the .NET Framework releases all Excel COM objects immediately.

    Edit: this is after you added more details to your question.

    In otherComponent you don’t need to release the Workbook and Document objects. These two objects are created in your first object which implies that the first object is the owner. Since it’s the first object that owns your top-level Excel objects (assuming you also have an Application object somewhere), your first object can call otherComponent, pass in Workbook and Document and then on return, clean them up. If you never use any of these objects in your MainComponent, then you should create the Excel-related objects inside otherComponent and clean them up there.

    With COM interop, you should create your COM objects as close to the place where you need them and release them explicitly as soon as you can. This is especially true for Office applications.

    I made this class to make using COM objects easier: this wrapper is disposable, so you can use using(...) with your COM objects – when the using scope is over, the wrapper releases the COM object.

    using System;
    using System.Runtime.InteropServices;
    
    namespace COMHelper
    {
        /// <summary>
        /// Disposable wrapper for COM interface pointers.
        /// </summary>
        /// <typeparam name="T">COM interface type to wrap.</typeparam>
        public class ComPtr<T> : IDisposable
        {
            private object m_oObject;
            private bool m_bDisposeDone = false;
    
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="oObject"></param>
            public ComPtr ( T oObject )
            {
                if ( oObject == null )
                    throw ( new ArgumentNullException ( "Invalid reference for ComPtr (cannot be null)" ) );
    
                if ( !( Marshal.IsComObject ( oObject ) ) )
                    throw ( new ArgumentException ( "Invalid type for ComPtr (must be a COM interface pointer)" ) );
    
                m_oObject = oObject;
            }
    
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="oObject"></param>
            public ComPtr ( object oObject ) : this ( (T) oObject )
            {
            }
    
            /// <summary>
            /// Destructor
            /// </summary>
            ~ComPtr ()
            {
                Dispose ( false );
            }
    
            /// <summary>
            /// Returns the wrapped object.
            /// </summary>
            public T Object
            {
                get
                {
                    return ( (T) m_oObject );
                }
            }
    
            /// <summary>
            /// Implicit cast to type T.
            /// </summary>
            /// <param name="oObject">Object to cast.</param>
            /// <returns>Returns the ComPtr object cast to type T.</returns>
            public static implicit operator T ( ComPtr<T> oObject )
            {
                return ( oObject.Object );
            }
    
            /// <summary>
            /// Frees up resources.
            /// </summary>
            public void Dispose ()
            {
                Dispose ( true );
                GC.SuppressFinalize ( this );
            }
    
            /// <summary>
            /// Frees up resurces used by the object.
            /// </summary>
            /// <param name="bDispose">When false, the function is called from the destructor.</param>
            protected void Dispose ( bool bDispose )
            {
                try
                {
                    if ( !m_bDisposeDone && ( m_oObject != null ) )
                    {
                        Marshal.ReleaseComObject ( m_oObject );
                        m_oObject = null;
                    }
                }
                finally
                {
                    m_bDisposeDone = true;
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say I have one table called REVIEWS This table has Reviews that customers
I have one field that I need to sum lets say named items However
Lets say that you have a business object whose current state implies that there
Lets say I have one cell A1, which I want to keep constant in
Let's say that I have the following code that's run in one thread of
Let's say I have one class Foo that has a bunch of logic in
Lets say that you have websites www.xyz.com and www.abc.com. Lets say that a user
Lets say that I have a header user control in a master page, and
Lets say that I have an executable and when it is started I want
Lets say that I have only DHT (distributed hash table) implemented (in Python), and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.