Do I need to release the COM object on every #39;foreach#39; iteration?(我是否需要在每次“foreach迭代时释放 COM 对象?)
问题描述
这是(潜在的)问题:
我创建了一个 COM 对象,然后使用foreach"遍历它返回的集合中的每个元素.我是否需要释放我在集合中遍历的每个单独元素?(见下面的代码.)如果是这样,我想不出一种方法可以有效地从finally"语句中释放它,以防在操作项目时出现错误.
I create a COM object, and then use a 'foreach' to iterate through each element in a collection it returns. Do I need to release each individual element I iterate through in the collection? (See code below.) If so, I can't think of a way to effectively to release it from within a 'finally' statement, just in case there is an error as the item is being operated upon.
有什么建议吗?
private static void doStuff()
{
ComObjectClass manager = null;
try
{
manager = new ComObjectClass();
foreach (ComObject item in manager.GetCollectionOfItems())
{
Log.Debug(item.Name);
releaseComObject(item); // <-- Do I need this line?
// It isn't in a 'finally' block...
// ...Possible memory leak?
}
}
catch (Exception) { }
finally
{
releaseComObject(manager);
}
}
private static void releaseComObject(object instance)
{
if (instance != null)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(instance);
}
catch
{
/* log potential memory leak */
Log.Debug("Potential memory leak: Unable to release COM object.");
}
finally
{
instance = null;
}
}
}
推荐答案
您不应该将 foreach
语句与 COM 对象一起使用,因为在您无法控制的幕后进行了引用过度释放.我会切换到 for
循环并确保您 永远不要在 COM 对象中使用两个点.
You should not use a foreach
statement with a COM object, as a reference is made behind the scenes to which you have no control over releasing. I would switch to a for
loop and make sure you never use two dots with COM objects.
看起来会是这样:
try
{
manager = new ComObjectClass();
ComObject comObject = null;
ComObject[] collectionOfComItems = manager.GetCollectionOfItems();
try
{
for(int i = 0; i < collectionOfComItems.Count; i++)
{
comObject = collectionOfComItems[i];
ReleaseComObject(comObject);
}
}
finally
{
ReleaseComObject(comObject);
}
}
finally
{
ReleaseComObject(manager);
}
这篇关于我是否需要在每次“foreach"迭代时释放 COM 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我是否需要在每次“foreach"迭代时释放 COM 对象?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01