如何在C#中处理托管和非托管对象?

时间:2015-11-19 13:57:42

标签: c# asp.net destructor dispose

所有。我从来没有使用析构函数也没有处理过,所以这对我来说是新的。 我的任务是执行一个具有析构函数和dispose方法的类,并且具有自动增量的UInt64 Id属性,以及必须由Id引用的静态Dictionary<UInt64,MyClass> < em> live MyClass的实例。

在搜索了如何正确使用它们之后,这就是我最终要做的事情:

public class MyClass : IDisposable
{
    private static Object Lock = new Object();
    private static Dictionary<UInt64, MyClass> LiveInstances = new Dictionary<UInt64, MyClass>();

    public UInt64 Id { get; private set; }

    public MyClass()
    {
        lock (Lock)
        {
            var newId = IncrementalId();
            if (newId == 0)
            {
                throw new ArgumentException("Reached MAX VAL");
            }
            Id = newId;
            LiveInstances.Add(Id, this);
        }
    }

    ~MyClass()
    {
       CleanUpNativeResources();
    }     

    public void Dispose()
    {
        lock (Lock)
        {
            CleanUpManagedResources();
            CleanUpNativeResources();
            GC.SuppressFinalize(this);
        }
    }

    protected virtual void CleanUpManagedResources()
    {
        LiveInstances.Remove(Id);

    }
    protected virtual void CleanUpNativeResources()
    {

    }

    private static UInt64 IncrementalId()
    {
        for (ulong i = 0; i <= Convert.ToUInt64(LiveInstances.Count) ; i++)
        {
            if (i != UInt64.MaxValue && !LiveInstances.ContainsKey(i + 1))
            {
                return i+1;
            }
        }
        return 0;
    }
}

现在,我的问题是 如何处置对象? 我是否试图找到处理对象的示例,我发现这样的事情:

 // Code to dispose the managed resources of the class
 Console.WriteLine("Object disposed");

提前致谢。

1 个答案:

答案 0 :(得分:4)

垃圾收集器会在某个时间点自动处理托管资源。非托管资源就像Filehandles一样,通过进行Windows API调用来获取,该API调用返回必须手动释放的Windows句柄。你没有任何需要手动处理的东西。    如果你不释放这些句柄,它们将在程序的持续时间内保持分配状态,但是所有具有非托管资源的.Net类都提供Finalizer(见下文)以确保它们通常被释放在某些时候。

(但是如果您正在编写自己的文件处理类并忘记在任何地方释放文件句柄,则文件将保持打开状态,直到您的程序退出。)

通常,这些非托管资源将在两个地方释放:

Dispose()方法。这应该是您处置非托管资源的正常方式。

终结者。这是一种最后的手段。如果一个类有一个终结器,它将在垃圾收集器清理一个死对象时调用它。如果程序员忘记调用Dispose(),那么任何具有非托管资源的类都应该有一个终结器来清理。

使用的基本Dispose模式如下:

class MyObject : IDisposable
{
    //indicates if dispose has already been called
    //private bool _disposed = false;

    //Finalize method for the object, will call Dispose for us
    //to clean up the resources if the user has not called it
    ~MyObject()
    {
        //Indicate that the GC called Dispose, not the user
        Dispose(false);
    }

    //This is the public method, it will HOPEFULLY but
    //not always be called by users of the class
    public void Dispose()
    {
        //indicate this was NOT called by the Garbage collector
        Dispose(true);

        //Now we have disposed of all our resources, the GC does not
        //need to do anything, stop the finalizer being called
        GC.SupressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        //Check to see if we have already disposed the object
        //this is necessary because we should be able to call
        //Dispose multiple times without throwing an error
        if (!disposed)
        {
            if (disposing)
            {
                //clean up managed resources
                components.Dispose();
            }

            //clear up any unmanaged resources - this is safe to
            //put outside the disposing check because if the user
            //called dispose we want to also clean up unmanaged
            //resources, if the GC called Dispose then we only
            //want to clean up managed resources
        }
    }
}