MCPD 70-536题目 非托管资源 释放

  You are creating a class that uses unmanaged resources. This class maintains references to managed resources on other objects. You need to ensure that users of this class can explicitly release resources when the class instance ceases to be needed. Which three actions should you perform? (Each correct answer presents part of the solution. Choose three.)

  你正在创建一个使用非托管资源的类。该类维持在其它对象上管理托管资源的引用。你需要确保停止类实例时能够确实释放资源。哪三个动作你会执行。(每个正确的答案提供方案的一部分。选择3个)

  ADefine the class such that it inherits from the WeakReference class.

  BDefine the class such that it implements the IDisposable interface.  (定义继存自IDisposable接口的类)

  CCreate a class destructor that calls methods on other objects to release the managed resources.

  DCreate a class destructor that releases the unmanaged resources.  (创建释放非托管资源的析构函数)

  ECreate a Dispose method that calls System.GC.Collect to force garbage collection.

  FCreate a Dispose method that releases unmanaged resources and calls methods on other objects to release the managed resources.   (创建Dispose方法用于释放非托管资源,并且在其它对象上调用此方法释放托管资源)

 

答案:BDF 

注:

  E:垃圾回收器(System.GC.Collect),只能释放托管资源,不能释放非托管资源

 

测试代码
  创建一个控制台应用程序。并建立ManageResource类,此类使用非托管资源handle。当类使用完后,释放非托管资源。

namespace  UnManageResource
{
    
class
 Program
    {
        
static void Main(string
[] args)
        {
            //使用完后释放资源
            
using (ManageResource umr = new
 ManageResource())
            {

            }

            ManageResource umrTry 
= new
 ManageResource();
            
//使用完后释放资源

            try
            {

            }
            
finally
            {
                
if (umrTry != null )
                {
                    umrTry.Dispose();
                }
            }
        }
    }

    
//继承IDisposable,用于释放资源

    class  ManageResource : IDisposable
    {
        
//非托管资源

        private  IntPtr handle;

        
//析构函数

        ~ ManageResource()
        {
            
//释放资源

            ReleaseResource();
        }

        
#region IDisposable Members


        
//显示释放未托管资源
        public void  Dispose()
        {
            
//释放资源

            ReleaseResource();

            
//不调用析构函数。由于用户是显示调用,所以资源释放不再由GC来完成

            GC.SuppressFinalize(this );
        }
        
#endregion


        
/// <summary>
        
///  释放资源方法
        
/// </summary>

        private void  ReleaseResource()
        {
            
//释放非托管资源

            handle =  IntPtr.Zero;
        }
    }
}

 

 

 

 

 

你可能感兴趣的:(资源)