Using Session to store Datatable

后端 未结 5 845
时光取名叫无心
时光取名叫无心 2021-01-13 19:04

currently we are using Sessions to store datatables in our pages so that we don\'t have to make Database hits to get the same datatable again and again. But my worry is that

5条回答
  •  时光说笑
    2021-01-13 19:31

    This is dependent on what is being stored in the datatables. In any case, I would use the ASP.NET Cache to store these datatables for the following reasons.

    • Cache has an expiry, which means you can automatically remove it based upon a sliding or absolute expiry timed value

    • Cache will automatically be removed if the processes memory "pressure" is too high.

    • You can make a cached item specific to one user, or global to all users based upon its key

    for example:

    // personalized cache item
    string personalCacheKey = string.Format("MyDataTable_{0}", (int)Session["UserID"]);
    DataTable myPersonalDataTable = (DataTable)Cache[personalCacheKey];
    
    if (myPersonalDataTable == null)
    {
        myPersonalDataTable = database.dosomething();
        Cache.Insert(personalCacheKey, myPersonalDataTable, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0)); // 30 minutes
    }
    
    // global (non user specific) cached item
    string globalCacheKey = "MyDataTable";
    DataTable globalDataTable = (DataTable)Cache[globalCacheKey];
    
    if (globalDataTable == null)
    {
        globalDataTable = database.dosomething();
        Cache.Insert(globalCacheKey, globalDataTable, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0)); // 30 minutes (again)
    }
    

    The issue that you have now, however, is if the underlying data gets updated, and whether it is acceptable for your application to present "old" cached data. If it is not acceptable, you will have to forcibly remove an item from cache, there are a few mechanisms for that.

    You can setup a SqlCacheDependency (which I have never personally used), or you can just clear out the cached object yourself using Cache.Remove(cachekey).

提交回复
热议问题