ArcEngine开发中出现“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”错误
在项目开发过程中,使用了要素的游标进行数据查询,在数据查询进行到一半的时候,系统报错“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”,在网上搜了一下问题,基本都是说“循环多次打开对象,导致内存没有及时释放。”的原因,需要将COM对象释放掉。
问题:
这是我游标代码部分,在游标中我循环调用了“getValueByOtherFeatureClass”方法,于是在这里我猜测,是这个方法循环调用太多,导致对象没有及时释放导致的内存溢出。(因为getValueByOtherFeatureClass这个方法里面也用了游标Cursor,所以能基本确认是这个问题)
解决方法:
由于在getValueByOtherFeatureClass方法我也用到了游标,故我在方法中添加“Marshal.ReleaseComObject”用于释放对象。每次调用完getValueByOtherFeatureClass方法,我都将该方法中的“IFeatureCursor 、IFeature、ISpatialFilter ”三个对象释放掉。这样的话,每次调用getValueByOtherFeatureClass方法,之前创建的对象都释放掉了,故多次循环不会出现报错!
(本文仅为自己AE开发过程中的学习笔记,大佬勿喷)
强调:
Marshal.ReleaseComObject(pMatchDataFeatureCursor);
Marshal.ReleaseComObject(pMatchDataFeature);
Marshal.ReleaseComObject(pSpatialFilter);
是关键!!!!
private string getValueByOtherFeatureClass(IFeatureClass pMatchDataFeatureClass,string matchDataFiled, string transDataFiled, string matchValue)
{
//①遍历要素数据 ==》pDataFeatureClass
// 创建polyline空间查询器
ISpatialFilter pSpatialFilter = new SpatialFilter();
pSpatialFilter.WhereClause = matchDataFiled + "=" +"\'" + matchValue + "\'";
//创建Feature要素游标,根据pSpatialFilter条件进行数据查询
IFeatureCursor pMatchDataFeatureCursor = pMatchDataFeatureClass.Search(pSpatialFilter, true);
IFeature pMatchDataFeature = pMatchDataFeatureCursor.NextFeature();
while(pMatchDataFeature != null)
{
int transDataIndex = pMatchDataFeature.Fields.FindField(transDataFiled);
string transValue = pMatchDataFeature.Value[transDataIndex].ToString();
//释放arcengine中的COM对象 ==及时处理COM对象,否则会报错!!!
Marshal.ReleaseComObject(pMatchDataFeatureCursor);
Marshal.ReleaseComObject(pMatchDataFeature);
Marshal.ReleaseComObject(pSpatialFilter);
return transValue;
}
//释放arcengine中的COM对象
Marshal.ReleaseComObject(pMatchDataFeatureCursor);
Marshal.ReleaseComObject(pSpatialFilter);
return null;
}