NET Caching Library Help
Async Example
Examples > Async Example

By default, items are saved and removed from the secondary cache synchronously as a blocking operation.  It is possible to increase the speed of saving and removing items in the cache by saving asynchronously.  The FileCacheProvider, SqliteCacheProvider, and SqlSeverCacheProvider all support asynchronous saving and removing.  Simply set IsAsyncSetAndRemove = true

Example

   

    public class AsyncExample

    {

       

        public void AsyncExampleUsage()

        {

            //Build parameters for the report

            Dictionary<string, object> parms = new Dictionary<string, object>();

            parms.Add("Month", DateTime.Now.Month);

            parms.Add("Year", DateTime.Now.Year);

 

            //Get the cache key based on the report parameters

            string cacheKey = Cache.Instance.BuildCacheKey("MonthlySalesReport", parms);

 

            //Get the report from the cache, if it does not exist, call the ReportLogic.MonthlySalesReport, save it to the cache and return it

            List<ReportDetail> result = Cache.Instance.Get<List<ReportDetail>>(cacheKey, NetCachingLibraryTest.ReportLogic.MonthlySalesReport, parms);

        }

    }

    public static class Cache

    {

        private static SmartCache _smartCache;

        public static FileCacheProvider SecondaryCache { get; set; }

        private static void Setup()

        {

            string cacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),

                "KellermanSoftware",

                "NetCachingLibrary",

                "AsyncExample");

            FileCacheProvider fileCacheProvider = new FileCacheProvider(cacheDirectory);

            fileCacheProvider.IsAsyncSetAndRemove = true;

            SecondaryCache = fileCacheProvider;

           

            SmartConfig config = new SmartConfig(new MemoryCacheProvider(), SecondaryCache);

 

            //Specify UserName and LicenseKey for Licensed Mode

            //config.UserName = "my user name";

            //config.LicenseKey = "my license key";

 

            _smartCache = new SmartCache(config);

        }

        public static SmartCache Instance

        {

            get

            {

                if (_smartCache == null)

                    Setup();

                return _smartCache;

            }

        }

    }

    public static class ReportLogic

    {

        //Example long running report

        public static List<ReportDetail> MonthlySalesReport(Dictionary<string, object> parms)

        {

            System.Threading.Thread.Sleep(1000);

            List<ReportDetail> list = new List<ReportDetail>();

            list.Add(new ReportDetail("Midwest", 233457.47m));

            list.Add(new ReportDetail("Southern", 234789.88m));

            return list;

        }

    }