日期:2014-05-18  浏览次数:21043 次

c# 非托管资源释放问题
现在我定义了一个静态类,通过此类访问非托管的第三方接口
C# code

 public  static class CBurdentVillageAPI
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="ptr">可执行程序句柄</param>
        /// <returns></returns>
       [DllImport("business.dll")]
       public static extern int init(IntPtr  ptr);

       /// <summary>
       /// 打开交易 
       /// </summary>
       /// <returns></returns>
       [DllImport("business.dll")]
       public static extern int open();

       /// <summary>
       /// 交易
       /// </summary>
       /// <returns></returns>
       [DllImport("business.dll")]
       public static extern int service();

       /// <summary>
       /// 关闭交易
       /// </summary>
       /// <returns></returns>
       [DllImport("business.dll")]
       public static extern int close();

        /// <summary>
       /// 返回错误信息 dll接口任何调用异常,可以使用该函数来返回错误信息
       /// </summary>
       [DllImport("business.dll")]
       public static extern void geterrormessage(StringBuilder  tradereturnmsg);
}



程序中是这样调用的
C# code

  public class CBurdentVillage :IDisposable 
{
  public bool GetPatiInfoForPati_Out_Visit(ref Global.strDaten dataset)
{
     CBurdentVillageAPI.open();
     ...//省略参数传递
       int Ret = CBurdentVillageAPI.service();
                if (Ret != 0)
                {
                    StringBuilder err = new StringBuilder(255);
                    CBurdentVillageAPI.geterrormessage(err);
                    DBPub.DataObj.ErrDes = err + "";
                    CBurdentVillageAPI.close();
                    return false;
                }
                else
                {
                  ...
                 }
}
}
 #region IDisposable 成员
        private bool m_disposed;

        void IDisposable.Dispose()
        {
            //throw new NotImplementedException();
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    //在这里释放托管对象

                }
                //在这里释放非托管对象      
            [color=#FF0000] 此处该如何操作?????[/color]                m_disposed = true;
            }
        }

        ~CBurdentVillage()
        {
            Dispose(false); 
        }



现在我想问一下,程序调用完成后该如何释放这个非托管的资源呢

------解决方案--------------------
这个好象没什么需要释放的资源啊
------解决方案--------------------
确保凡是以前没有调用过Close的,在Dispose中再调用Close呗。
------解决方案--------------------
调用close(),是不是有别的操作,应该咨询business.dll的编写者。
------解决方案--------------------
探讨

CBurdentVillageAPI.close()只是调用接口里面的关闭交易

我现在想问的时候我如何释放非托管的资源