.net使用Com组件的问题

前段时间,在.net中使用Supermap组件(activeX)时,发现经常出现内存不能写的异常,后来与超图公司联系,说是需要在代码中释放Com对象才可以。
今天在使用MapX组件时,又发现一个比较奇怪的问题:在处理拓朴关系时,处理部分数据后,出现NullReferenceException异常。代码如下所示:

 for (int i=1;i<=axMap1.Layers[LayerName].AllFeatures.Count;i++)
{
    MapXLib.Feature ft=axMap1.Layers[LayerName].AllFeatures[i];
    x1 =  ft.Parts[1].get_X(1) ;
    y1 =  ft.Parts[1].get_Y(1);
    ProcessData(x1,y1);
}
查了半天,也没有找到原因所在,后来想到可能与Com对象的释放有关,于是将代码调整为:
MapXLib.Layer lay=axMap1.Layers[LayerName];
MapXLib.Features fs= lay.AllFeatures;
int c=fs.Count;
for (int i=1;i<=c;i++)
{
    MapXLib.Feature ft=fs._Item(i);
    MapXLib.Parts pts=ft.Parts;
    MapXLib.Points pss=pts [1];
    x1 =  pss.get_X(1) ;
    y1 =  pss.get_Y(1);
    ProcessData(x1,y1);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(pss);
    pss=null;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(pts);
    pts=null;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(ft);
    ft=null;
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(fs);
fs=null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(lay);
lay=null;


调整后的代码运行正常。

在调整期间发现几个值得注意的地方:
1、只要是定义了Com对象,在使用完之后必须释放,否则,多次调用后,将出现问题。
2、中间临时变量也需要释放,如将
    x1 =  ft.Parts[1].get_X(1) ;
    折为
    MapXLib.Parts pts=ft.Parts;
    MapXLib.Points pss=pts [1];
    x1 =  pss.get_X(1) ;
    y1 =  pss.get_Y(1);
    再释放变量。
3、如果某方法返回了Com对象,则需要定义返回的变量,然后将其释放。


另外,发现使用FireFox浏览器时,博客圆的浏览和编辑blog就存在一些问题了。

posted on 2005-02-07 22:01  wljcan  阅读(2648)  评论(1编辑  收藏  举报

导航