. NET common memory leak issues--GC, delegate events, and weak references

Source: Internet
Author: User

In fact, memory leaks have always been a headache, and this has been a big improvement in the language with the GC, but there may still be problems.

First, what is memory leak (leak)?

Memory leaks do not mean that memory is not broken, or memory is not plugged in, simply, memory leaks is in the time you expect your program to occupy the memory is not as you imagine the release.

So what is the time you expect? It's important to understand this. If an object takes up memory for as long as the program that contains the object, you don't expect it to. Then you can think of a memory leak. Use specific examples to illustrate the following:

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;      }}

In the above code, we used a static event, and the lifetime of the static member begins with the AppDomain being loaded, until the AppDomain is unloaded, that is, in general, if the process is not closed and you forget to unregister the event, Then the object referenced by the EventHandler delegate that the ButtonClick event contains will persist until the end of the process, which creates a memory leak problem. That's the same. One of the causes of the most common memory leak problems in net. I'll go on to talk about how to deal with the leaks caused by such incidents.

Second, the way of memory recovery

1. Reference counting

The meaning of the reference count is the number of times each value is referenced by the tracking record. When a variable is declared and a reference type value is assigned to the variable, the number of references to that value is 1. If the same value is assigned to another variable, the number of references to that value is added by 1. Conversely, if a variable that contains a reference to this value has another value, the number of references to the value is reduced by 1. When the number of references to this value becomes 0 o'clock, it means that there is no way to access the value again, so that it can reclaim the memory space it occupies. That way, when the garbage collector runs again next time, it frees the memory used by those values that have a zero reference count.

Like the original IE6, the way JavaScript native object memory is reclaimed is to determine whether an object is garbage by checking whether the object has a reference. Before IE9, the objects in its BOM and Dom were implemented in the form of COM objects using C + +, and the garbage collection mechanism of COM objects was also a reference counting strategy. This is usually caused by a circular reference that causes a memory leak, which is a reference to B, and B also refers to a. There are also problems with this circular reference in Objective-c. The solution in Objective-c is to mark a party as weak, which can be described here, about the delegate mode in Objective-c.

2. Mark Removal Method (Mark-weep)

In C #, the notation is used to reclaim memory, all objects are marked, and are not marked once. Judging whether an object is garbage depends on having a reference, but rather whether it is referenced by the root.

The root type has variables in the register, variables on the thread stack, static variables, and so on.

Let's take a look at a typical object graph with a circular reference in the diagram.

Let's take some of these diagrams to illustrate

In the implementation of the tag purge policy, since the function executes, local3 out of the scope, so this mutual reference is not a problem in the markup cleanup method.


It's easy to see that because each object has a mark, creating a large number of small objects can put a strain on the mark stage. It is important to note that all threads are suspended during the mark and weep phases of the GC, so creating a large number of threads can also cause problems with the GC. I'll discuss the problem later.

Third, weak references to solve some problems

As previously mentioned, forgetting to unregister an event is usually. NET is the most common memory leak problem, how can we solve this problem automatically? This means that when the object to which the method belongs is already marked as garbage, we will unregister the method in the event. This can be achieved by a weak reference.

The essence of a delegate is a class that contains several key attributes:

1. Point to the original object's target property (strong reference).

2. A ptr pointer to a method.

3. A collection is maintained internally (delegate is implemented as a linked list structure).

Because. NET is a strong reference, we want to change it to a weak reference, we can seize these characteristics, create a own weakdelegate class.

The essence of an event is an accessor method, and the relationship to the delegate is similar to a field and property, that is, to control external access to the field. We can convert external delegates to our own defined delegates by customizing the Add and Remove methods.

public class button{Private class Weakdelegate {public WeakReference Target;    Public MethodInfo Method;    } private list<weakdelegate> clicksubscribers = new list<weakdelegate> ();                Public event EventHandler Click {add {clicksubscribers.add (new Weakdelegate { Target = new WeakReference (value. Target), Method = value.        Method});    } Remove {...}        } public void FireClick () {list<weakdelegate> toremove = new list<weakdelegate> (); foreach (weakdelegate subscriber in clicksubscribers) {///The first target represents the object to which the method belongs, and the second target indicates whether the object is marked as garbage, or null if it is            Indicates that it has been marked as garbage. Object target = Subscriber.            Target.target;            if (target = = null) {Toremove.add (subscriber); } else {Subscriber. Method.invoke (target, new object[] {thiS, eventargs.empty});    }} clicksubscribers.removeall (Toremove); }}

Weak references can also be used to create an object pool that reduces memory and GC stress by managing a small number of objects. We can represent the smallest number of objects in an object pool by a strong reference, with a weak reference to represent the maximum number that can be reached.

. NET common memory leak issues--GC, delegate events, and weak references

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.