.NetGurus

Diğer Yazılar

Google a Ekle

Add to Google



Caching In Winforms With Expiration

Hi here is the sample code of a cache manager class. It is prepared to have a simple mechanism like the Cache class of the Asp.Net.  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

public class CacheManager
{
    static System.Collections.Hashtable ht = new System.Collections.Hashtable();

    public static void AddItem(string key, object value, uint timeToCache)
    {
        if (timeToCache > 3600)
            throw new ArgumentOutOfRangeException("Cache süresi 1 saatten uzun olamaz.");

        System.Threading.Timer t = new System.Threading.Timer(new TimerCallback(TimerProc));
        t.Change(timeToCache * 1000, System.Threading.Timeout.Infinite);
        ht.Add(t, key);
        AppDomain.CurrentDomain.SetData(key, value);
    }

    public static object GetItem(string key)
    {
        return AppDomain.CurrentDomain.GetData(key);
    }

    private static void TimerProc(object state)
    {
        System.Threading.Timer t = state as System.Threading.Timer;

        if (t != null)
        {
            object key = ht[t];
            ht.Remove(t);
            t.Dispose();

            if (key != null)
                AppDomain.CurrentDomain.SetData(key.ToString(), null);
        }
    }
}

And the usage;

	CacheManager.AddItem(cacheKey, myDataTable, 300);

Posted by yavuz on 11 Mart 2010 Perşembe 00:58
Permalink | Yorumlar (0) | Post RSSRSS comment feed