您的位置:首页 > 编程语言 > C#

understanding in the memory management in C#

2009-01-12 11:56 387 查看
As we known, CLR provides a good and effective service--automatic memory management during managed execution. We can leave it to the .net itself. However, unmanaged resources won’t be processed automatic, because it is out the CLR’s control. First, I’d like to focus on unmanaged resources.

using System;
public class Stack{
private Node first = null;
public bool Empty {
get {
return (first == null);
}
}
public object Pop() {
if (first == null)
throw new Exception("Can't Pop from an empty Stack.");
else{
object temp = first.Value; // the top element out.
first = first.Next; //the pointer point to the next element.
return temp;
}
}
public void Push(object o) {
first = new Node(o, first);
}
private class Node
{
public Node Next;
public object Value;
public Node(object value) : this(value, null) { }
public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
}
It’s a stack class, in which there is a subclass node. In fact, it’s a chained list of the node instance. The node instance is born in the method of push(). The garbage collection won’t process it until we don’t use it any more. The instance will be an object of the garbage collection when it is inaccessible to any code.

class Test
{
static void Main()
{
Stack s = new Stack();
for (int i = 0; i < 10; i++) //initialize
s.Push(i);
for (int i = 0; i < 10; i++)
System.Console.WriteLine(s.Pop());
s = null;
System.Console.WriteLine();
}
}
This shows a stack instance in the main method. We initialize the stack class with 10 elements, and then print it. At the last, it’s evaluated null. After that, both the stack and the instance is fit for the condition of the garbage collection and can be easily cleared up.
However, sometimes, we need make sure that release the managed resources under the condition without executing the garbage collection(cause it really need to release part of the resources, while the garbage collection wastes a lot of system resources.), or the unmanaged resources. What should we do? The answer is taking the dispose() and the Destructors method.

public class ResourceHolder : System.IDisposable
{
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
// avoid the garbage collection calling the method of the class.
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// release the managed resources here.
}
// release the unmanaged resources here.
}
~ResourceHolder()
{
Dispose(false);
}
}

Here we call Dispose() but the method Dispose(bool) works successfully to release the resources rather than Dispose(). With Dispose(true),we can release both of the resources. So why need a Destructors? In fact, Destructors is a spare method, if we forget to use
Dispose(),Destructors can save us.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: