Simple Object cache manager (C # implementation)

Source: Internet
Author: User

It's been almost two years since the dish was launched. record your own things during your work. at the same time, I hope that you can give us valuable advice through the guidance of prawns. It is a great honor to be able to inspire or help fellow friends.

Put an object cache first. Generally, some objects are often used, but they must be created every time they are used. If the creation process is complex (such as creating through a complex algorithm, for example, if you need to find the entity class of the database, it will consume CPU usage for multiple times. Therefore, we plan to save these objects in the memory, A Dynamic Time period survival mark is given to each object. When it is called again within this time period, it no longer needs to be re-created and pulled. Instead, it is read directly from the memory and the code is put below, the cache is thread-safe and does not need to be locked when storing objects.

 

Code

 

/// <Summary>
/// Read the flag class
/// </Summary>
Public class ReadFlag
{
Private int readCount;
/// <Summary>
/// Number of reads
/// </Summary>
Public int ReadCount
{
Get {return readCount ;}
Set {readCount = value ;}
}

Private DateTime lastReadTime;
/// <Summary>
/// Last read time
/// </Summary>
Public DateTime LastReadTime
{
Get {return lastReadTime ;}
Set {lastReadTime = value ;}
}

Public ReadFlag (DateTime birthTime)
{
This. readCount = 0;
This. lastReadTime = birthTime;
}
}

Public class ElementBuffer <TKey, Tobject>
{
Public Dictionary <TKey, ReadFlag> ReadFlagBuffer = new Dictionary <TKey, ReadFlag> ();
Public Dictionary <TKey, Tobject> Buffer = new Dictionary <TKey, Tobject> ();
}

/// <Summary>
/// Object Cache
/// </Summary>
/// <Typeparam name = "TKey"> </typeparam>
/// <Typeparam name = "Tobject"> </typeparam>
Public class ObjectCache <TKey, Tobject>
{
Private int objectCount = 100;
/// <Summary>
/// Maximum number of objects allowed in the cache
/// </Summary>
Public int ObjectCount
{
Get {return objectCount ;}
Set {objectCount = value ;}
}

Private int loseTime = 100;
/// <Summary>
/// Expiration time, in seconds
/// </Summary>
Public int LoseTime
{
Get {return loseTime ;}
Set {loseTime = value ;}
}

Private ElementBuffer <TKey, Tobject> buffer = new ElementBuffer <TKey, Tobject> ();

Public object this [TKey key]
{
Get
{
Tobject ret;
If (this. buffer. ReadFlagBuffer. ContainsKey (key) & this. buffer. Buffer. TryGetValue (key, out ret ))
{
Lock (this. buffer)
{
This. buffer. ReadFlagBuffer [key]. ReadCount ++;
This. buffer. ReadFlagBuffer [key]. LastReadTime = DateTime. Now;
}
Return ret;
}
Else
{
Return null;
}
}
Set
{
Tobject ret;
If (this. buffer. ReadFlagBuffer. ContainsKey (key) & this. buffer. Buffer. TryGetValue (key, out ret ))
{
Ret = (Tobject) value;
}
Else
{
Lock (this. buffer)
{
If (this. buffer. ReadFlagBuffer. Count> this. objectCount)
{
TKey removeKey;
TKey [] array = new TKey [this. buffer. ReadFlagBuffer. Keys. Count];
This. buffer. ReadFlagBuffer. Keys. CopyTo (array, 0 );
RemoveKey = array [0];
Foreach (TKey tkey in this. buffer. ReadFlagBuffer. Keys)
{
If (this. buffer. ReadFlagBuffer [tkey]. LastReadTime. AddSeconds (this. LoseTime). CompareTo (DateTime. Now) <0)
{
RemoveKey = tkey;
Break;
}
If (this. buffer. ReadFlagBuffer [tkey]. ReadCount <this. buffer. ReadFlagBuffer [removeKey]. ReadCount)
{
RemoveKey = tkey;
}
}
This. Remove (removeKey );
}
Else
{
ReadFlag readFlag = new ReadFlag (DateTime. Now );
This. buffer. ReadFlagBuffer. Add (key, readFlag );
This. buffer. Buffer. Add (key, (Tobject) value );
}
}
}
}
}

Private void Remove (TKey key)
{
Lock (this. buffer)
{
This. buffer. Buffer. Remove (key );
This. buffer. ReadFlagBuffer. Remove (key );
}
}
}

 

 

 

The above ReadFlag is a flag class. Each object stored in the object manager will obtain a corresponding flag to describe it. The flag object has two attribute values, which are the number of reads of the corresponding object, there is also the last access time. The constructor parameter is the object generation time. The last access time is based on the last read time when the manager is running. Select the object that is farthest from the current time to delete it, and control the number of objects in the memory.

ObjectCache is the cache manager, which is easy to use.

Static ObjectCache <string, T> Buffer = new ObjectCache <string, T> (); Create a cache first. Here, the key value uses the string type. We recommend using this type, or int and other simple types are the best.

Then we can use the string-type parameter key to obtain the object we store, that is, Buffer [key] as T;

Similarly, we can save the object (note that it must be a T type object) into the Buffer, Buffer [key] = object;

The cache manager has two attributes that can be customized and have default values, which are the maximum number of objects allowed by the manager, and the other is the expiration time, that is, when the number of objects reaches the maximum value allowed by the manager, the objects beyond the expiration time will be replaced.

 

 

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.