C # consider using weak references for large objects,

Source: Internet
Author: User

C # consider using weak references for large objects,

1. No matter how hard we try, we always use some data that requires a large amount of memory, and these memories do not need to be accessed frequently. Maybe you need to find a specific value from a large file, or the algorithm needs a large query table. In this case, you may not be able to use the second method. The first method is to create a local variable and generate a large chunk of garbage every time you execute the algorithm; the second is to create a member variable, which occupies this large block of memory for a long time. These two methods are often not very good.

2. Is there a good choice to solve this problem? The answer is to create a weak reference. The weak reference object is similar to the spam object. The program will tell the spam collector that the object can be recycled, but you still have a reference before the collection, it can be used to access this object as needed. If this policy can be reasonably used, the weak reference will work with the garbage collector to optimize memory usage. Code Description:

/// <Summary> /// large object type /// </summary> public class MyLargeClass {private int [,] matrix; private ushort matrixXDimension; private ushort matrixYDimension; public string reallyLongMessage; private static WeakReference _ weakObj; public static object WeakObj {get {return _ weakObj ?. Target; // "?." The syntax is a new feature of C #6.0, corresponding to. Net Framework 4.6. Indicates that if it is null, null is returned. If it is not null, the corresponding property value is obtained.} set {_ weakObj = new WeakReference (value ); // weak reference creation} public MyLargeClass (ushort matrixXDimension, ushort matrixYDimension) {this. matrixXDimension = matrixXDimension; this. matrixYDimension = matrixYDimension; matrix = new int [matrixXDimension, matrixYDimension];} private void Initialize () {// TODO perform more data initialization // load the data of the matrix two-dimensional array} public long Calculate () {// TODO process matri Return matrixXDimension * matrixYDimension * 1000;} public static void Execute () {// obtain a large object from a weak reference. If no weak reference or weak reference has been recycled, in this case, you need to recreate the object. MyLargeClass myLargeObject = WeakObj as MyLargeClass; // myLargeObject can be a local variable or a member variable if (myLargeObject = null) {myLargeObject = new MyLargeClass (1000,100 0 );} // TODO processes the data in the myLargeObject object // after processing, the large object is classified as weak reference, and then the myLargeObject is set to null, which indicates that the large object is not referenced. At this time, the system will think that the object pointed to by myLargeObject can be garbage collected. If the garbage collector is running at this time, the object will be recycled. However, if you need this object again before recycling, you only need to process the above four lines of code. WeakObj = myLargeObject; myLargeObject = null ;}}

3. from the code in the Execute () method, we can see that the use and cleanup of objects are handed over to the runtime for processing. This is a simple application scenario, but in many cases, the reality is not that simple, few objects are completely isolated from the outside world. Any large object contains references to other objects. If a large object is marked as a weak reference, its internal reference object will also be marked as a weak reference. The marked weak reference object will be recycled (not immediately recycled ).

4. Weak references should not be used for objects that implement IDisposable, because released objects cannot be weak references and you cannot call Dispose () in weak references (). Therefore, weak references should be used with non-IDisposable large objects.

Related Article

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.