C # weak references

Source: Internet
Author: User

Garfield just have a little faith. C # weak reference

The. NET Framework provides another interesting feature that is used to implement a variety of high-speed caches. Weak references in. NET are implemented through the system. weakreference class. Weak references provide a mechanism for referenced objects to enable the referenced objects to be destroyed.

Role of the collector. ASP. NET cache uses weak references. If the memory usage is too high, the cache will be cleared.

The forced garbage collection. NET Framework provides developers with the system. GC class to control some aspects of the garbage collector. Garbage collection can be enforced by calling the GC. Collect method. We recommend that you do not manually call the garbage collector, but set it to an automatic method. In some cases, developers may find that forced garbage collection will boost performance. However, you need to be very careful when using this method, because the current execution thread will be delayed when the garbage collector is running. The GC. Collect method should not be located in a location that may be frequently called. This will degrade the application's performance.

 

Constructor:

Weakreference initializes a new instance of the weakreference class. This constructor overload cannot be implemented in Silverlight-based applications.

Weakreference (object) references a specified object to initialize a new instance of the weakreference class.

Weakreference (object, Boolean) initializes a new instance of the weakreference class, references a specified object, and uses the specified resurrection trail.

Attribute:

Isalive indicates whether the objects referenced by the current weakreference object have been recycled.

Target gets or sets the object referenced by the current weakreference object (target ).

Trackresurrection indicates whether the object referenced by the current weakreference object will be tracked after it is terminated.

 

When we consider using weak references:

Objects may be used later, but they are not very definite. (If you are sure you want to use it, use strong references)

If necessary, the object can be re-constructed (for example, database construction ).

Objects occupy relatively large memory (generally larger than several KB)

 

In some cases, for example, when caching some big data objects, you may encounter a dilemma of memory and time. If you make large objects expire too quickly, each object creation consumes too much performance, if too many large objects are maintained

Memory will be used up, but the speed will be reduced. If the memory is sufficient, GC will not recycle the memory occupied by large objects, so weak references are reachable, that is, this object can be reused to achieve the purpose of caching. If the memory is insufficient, GC will have to recycle those large objects to release the memory space.

 

The following code example demonstrates how to use weak references to maintain the object cache as the application resource. This cache is built using the idictionary (of tkey, tvalue) of the weakreference object with the index value as the keyword. The target attribute of a weakreference object is an object in a byte array that represents data.

In this example, objects in the cache are randomly accessed. If an object is recycled through garbage collection, a new data object is generated. Otherwise, the object is accessible due to weak references.

Using system; using system. collections. generic; public class program {public static void main () {// create the cache. int cachesize = 50; random r = new random (); cache c = new cache (cachesize); string dataname = ""; // randomly access objects in the cache. for (INT I = 0; I <C. count; I ++) {int Index = R. next (C. count); // access the object by // getting a property value. dataname = C [Index]. name;} // show results. double regenpercent = C. regenerationcount * 100/C. count; console. writeline ("cache size: {0}, regenerated: {1} %", C. count. tostring (), regenpercent. tostring () ;}} public class cache {// dictionary to contain the cache. static dictionary <int, weakreference> _ cache; // track the number of times an // object is regenerated. int regencount = 0; Public cache (INT count) {_ cache = new dictionary <int, weakreference> (); // Add data objects with a // short weak reference to the cache. for (INT I = 0; I <count; I ++) {_ cache. add (I, new weakreference (new data (I), false) ;}// returns the number of items in the cache. public int count {get {return _ cache. count; }}// returns the number of times an // object had to be regenerated. public int regenerationcount {get {return regencount ;}// accesses a data object from the cache. // if the object was reclaimed for garbage collection, // create a new data object at that index location. public Data this [int Index] {get {// obtain an instance of a Data // object from the cache of // of weak reference objects. data d = _ cache [Index]. target as data; If (D = NULL) {// object was reclaimed, so generate a new one. console. writeline ("regenerate object at {0}: yes", index. tostring (); D = new data (INDEX); regencount ++;} else {// object was obtained with the weak reference. console. writeline ("regenerate object at {0}: No", index. tostring ();} return D ;}}// this class creates byte arrays to simulate data. public class data {private byte [] _ data; private string _ name; Public Data (INT size) {_ DATA = new byte [size * 1024]; _ name = size. tostring ();} // simple property. public string name {get {return _ name ;}}// example of the last lines of the output :////... // regenerate object at 36: Yes // regenerate object at 8: Yes // regenerate object at 21: Yes // regenerate object at 4: Yes // regenerate object at 38: no // regenerate object at 7: Yes // regenerate object at 2: Yes // regenerate object at 43: Yes // regenerate object at 38: No // cache size: 50, regenerated: 94% //

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.