Go to a weak reference cache class

Source: Internet
Author: User

When you optimize performance, you often use the cache class. The. NET framework provides a cache class in System.Web.dll. It's very useful in web development, but it doesn't work if it's WinForm development.
In. NET, developers do not care about the allocation of memory due to the existence of garbage collection mechanisms. Unused objects GC is automatically treated as garbage collection. It's easy to save money and improve performance if you can use the waste.
A Weakreferencecachepool<tkey, titem> class is provided below:


Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;
Using System.Runtime.ConstrainedExecution;

Namespace Cachedemo
{
#region the Weakreferencecachepool<tkey, Titem> class

public class Weakreferencecachepool<tkey, titem> where Titem:class
{
#region the Cleaner class

Private Class Cleaner:criticalfinalizerobject
{
#region Instance Data

Private Weakreferencecachepool<tkey, titem> _owner;

#endregion

#region Constructor & Finalizer

Public Cleaner (Weakreferencecachepool<tkey, titem> owner)
{
This._owner = owner;
}

~cleaner ()
{
if (This._owner._autocleanabandoneditems)
{
This._owner. Cleanabandoneditems ();
Gc. ReRegisterForFinalize (this);
}
}

#endregion
}

#endregion

#region Instance Data

Private Const int LOCK_TIMEOUT_MSECS = 500;
Private Dictionary<tkey, weakreference> _cachepool;
private bool _autocleanabandoneditems;
Private ReaderWriterLockSlim _cachelock;

#endregion

#region Constructor & Finalizer

Public Weakreferencecachepool (): This (true) {}

Public Weakreferencecachepool (bool autocleanabandoneditems)
{
This._cachelock = new ReaderWriterLockSlim ();
This._cachepool = new Dictionary<tkey, weakreference> ();
This._autocleanabandoneditems = Autocleanabandoneditems;
if (This._autocleanabandoneditems)
{
New Cleaner (this);
}
Else
{
Gc. SuppressFinalize (this);
}
}

~weakreferencecachepool ()
{
This._autocleanabandoneditems = false;
}

#endregion

#region Properties

public bool Autocleanabandoneditems
{
Get
{
return this._autocleanabandoneditems;
}
}

Public TItem This[tkey Key]
{
Get
{
if (key = = null)
{
throw new ArgumentNullException ("key");
}

if (This._cachelock.tryenterreadlock (lock_timeout_msecs))
{
Try
{
WeakReference WeakReference;
if (_cachepool.trygetvalue (key, out WeakReference))
{
Return (TItem) Weakreference.target;
}
}
Finally
{
This._cachelock.exitreadlock ();
}
}

return null;
}
Set
{
This. ADD (key, value);
}
}

#endregion

#region Methods

public void Add (TKey key, TItem Item)
{
if (key = = null)
{
throw new ArgumentNullException ("key");
}

if (item = = NULL)
{
throw new ArgumentNullException ("item");
}

if (This._cachelock.tryenterwritelock (lock_timeout_msecs))
{
Try
{
_cachepool[key] = new WeakReference (item);
}
Finally
{
This._cachelock.exitwritelock ();
}
}
}

public void Remove (TKey key)
{
if (key = = null)
{
throw new ArgumentNullException ("key");
}

if (This._cachelock.tryenterwritelock (lock_timeout_msecs))
{
Try
{
This._cachepool.remove (key);
}
Finally
{
This._cachelock.exitwritelock ();
}
}
}

public void Clear ()
{
if (This._cachelock.tryenterwritelock (lock_timeout_msecs))
{
Try
{
This._cachepool.clear ();
}
Finally
{
This._cachelock.exitwritelock ();
}
}
}

public void Cleanabandoneditems ()
{
if (This._cachelock.tryenterwritelock (lock_timeout_msecs))
{
Try
{
Dictionary<tkey, weakreference> newcachepool = new Dictionary<tkey, weakreference> ();
foreach (Keyvaluepair<tkey, weakreference> KeyValuePair in _cachepool)
{
if (keyValuePair.Value.IsAlive)
{
Newcachepool[keyvaluepair.key] = Keyvaluepair.value;
}
}

This._cachepool = Newcachepool;
}
Finally
{
This._cachelock.exitwritelock ();
}
}
}

#endregion
}

#endregion
}



The following is my summary of the use of weakreference to do the advantages and disadvantages of caching, welcome to shoot bricks ...

Caching with WeakReference can provide the following benefits:
1, as with the normal cache, can bring performance gains
2, does not affect cache objects being garbage collected
3, because it is waste utilization, it can be said not to occupy more memory, that is, save memory
4, due to the existence of GC recovery mechanism, can automatically handle the balance between memory consumption and performance
5, other ...

Caching with WeakReference can have the following drawbacks:
1, hit rate is affected by GC recovery mechanism, uncertain
2, other ...

Also, this article is an example of using WeakReference to do caching, "one-time improvement of 300% optimization practice."

Small tip:
GC can be used appropriately. KeepAlive (Cachedobject) to avoid cachedobject being recycled by GC.

-------------
P.S.
Cachedobject is the one that was weakreference track, such as:
WeakReference wf = new WeakReference (cachedobject);

Go to a weak reference cache class

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.