简体   繁体   English

我应该在离开方法之前将com对象设置为null吗

[英]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. 我有一个我在c#中引用的vb6对象,即Process,它具有一组操作。

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? 退出功能之前,我是否需要将operation设置为null? 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? 附带说明一下,如果需要,我该如何处置com对象?

Do I need to set operation to null before exiting the function? 退出功能之前,我是否需要将operation设置为null?

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. 当方法存在时,即使不将其设置为null, operation变量也将超出范围。

A COM object that is used from managed languages is disposed of automatically when it is finalized by the garbage collector. 从托管语言使用的COM对象在由垃圾回收器最终确定后会自动处理。 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). 这意味着,当没有人持有对COM对象的引用时,该对象将在一段时间后释放(取决于垃圾收集器决定何时插入并最终确定该对象)。

However, if you want to release the COM object immediately, you can invoke Marshal.ReleaseComObject . 但是,如果要立即释放COM对象,则可以调用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. 您想要使用Marshal.ReleaseComObject的唯一原因是该对象拥有非常稀缺的资源,您无须等待垃圾回收器为您释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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