Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Web =>  ASP.NET

About .NET memory leak--GC,Delegate and weak reference

  Peter      2013-05-25 12:59:09      3,122    0

Memory leak is always a headache for many programmers, the situation is much better now in some languages which have GC mechanism, but still we may face some memory leak issues when we write programs.

1. What is memory leak?

Memory leak is not that the memory chip is broken. In short, it's about that the memory requested is not released at the expected time as an expect way.

So what is the expected time? This is very important for you to understand memory leak. If the time an object taking the memory is the same as the time the program runs, but you don't expect it to be like this, then memory leak may happen. For example:

class Button {
  public void OnClick(object sender, EventArgs e) {

class Program {
  static event EventHandler ButtonClick;
  static void Main(string[] args) {

      Button button = new Button();
      ButtonClick += button.OnClick;

The above code has a static event, the life cycle of the static variable starts when the AppDomain is loaded and it ends until the AppDomain is unloaded, it means usually if the process is not ended and the developer forgets to deregister the event, then the object referenced by the EventHandler delegate of ButtonClick event will continue to exist until the program ends, this causes memory leak. This is also one of the most frequently seen memory leaks in .NET. 

2. Garbage collection methods

a. Reference counting

Reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource. It may also refer, more specifically, to a garbage collection algorithm that uses these reference counts to deallocate objects which are no longer referenced.

The garbage collection method of native object in JavaScript of IE 6 is reference counting. Before IE 9, BOM and DOM objects are implemented using COM objects written in C++, the garbage collection method of COM object is also reference counting. This method will introduce memory leak if there is reference cycle,i.e. if object references object B and at the same time object B references object A.

2. Mark and sweep

In C#, this method is used. All objects are marked and they will be marked only once.

Let's take a look at one graph about mark and sweep algorithm.

We illustrate part of the graph. In the implementation of mark and sweep, when the function finishes executing, local3 is popped out from the stack and it is out of the execution scope, hence the cyclic reference will be recycled.

3. Weak reference

As mentioned above, forgetting to deregister event s one of the most frequently seen memory leak in .NET. How do we automatically solve this issue? This requires that we will deregister the event when the object which contains the method is marked as garbage. This can be realized using weak reference.

In fact delegate is just a class, it contains some key properties:

1. The original object(target)

2. One pointer ptr which points to the method

3. An internal collection

Since delegate in .NET is strong reference, we need to convert it into weak reference. We can create our own WeakDelegate class.

We can use add and remove methods to convert the outside delegate into our own delegate. Below is the complete source code:

public class Button
    private class WeakDelegate
        public WeakReference Target;
        public MethodInfo Method;

    private List clickSubscribers = new List();

    public event EventHandler Click
            clickSubscribers.Add(new WeakDelegate
                Target = new WeakReference(value.Target),
                Method = value.Method

    public void FireClick()
        List toRemove = new List();
        foreach (WeakDelegate subscriber in clickSubscribers)
            object target = subscriber.Target.Target;

            if (target == null)
                subscriber.Method.Invoke(target, new object[] { this, EventArgs.Empty });

Weak reference can be used to create object pool, object pool can reduce memory and GC pressure by managing less objects. We can use strong reference to represents the smallest number of objects in the object pool and use weak reference to represent the largest number of objects in the object pool.

Source :



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


Crazy Atom Plugin

By sonic0002