简体   繁体   中英

Should I set com objects to null before leaving a method

I have a vb6 object that I am referencing in c# ie Process, that has a collection of operations.

I have the method

public double GetWidth(Process process, String operationName)
{
   Operation operation=process.GetOperation(operationName);
   return operation.GetValue("Width");
}

Do I need to set operation to null before exiting the function? I don't want to dispose of process or and objects that it contains but i am not sure if the operation instance will cause when I eventually need to dispose of process.

On a side note how do I dispose of a com object if I need to?

Do I need to set operation to null before exiting the function?

No you don't. When the method exists, the operation variable will be out of scope even if you don't set it to null.

A COM object that is used from managed languages is disposed of automatically when it is finalized by the garbage collector. This means that when no one holds a reference to the COM object any longer, the object will be released after some time (depending on when the garbage collector decides to kick in and finalize the object).

However, if you want to release the COM object immediately, you can invoke Marshal.ReleaseComObject . You may want to read about this method to understand when you should use it.

The only reason why you would want to use Marshal.ReleaseComObject is that the object holds a very scarce resource and you can't afford to wait for the garbage collector to release it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM