开发者

How to hold current date in cache, yet not compromise efficiency - asp.net

I am building a web application using asp.net (c#) and lingtosql. When I perform update operations on my db I update my classes. I use gridview to bind to update information. When I relay solely on the database the page's take very long to load. When I relay solely on the cache, I have old data. What workarounds do I have for have asynchronous cache updating, yet not overload the开发者_如何学运维 database with endless requests (I'd like to update the cache only if there has been a change in the database itself, and perform the update operation asynchronously).

Thanks alot,


You can have something like if the cache was inactive in a certain time(e.g. 30 minuntes) it'll refresh the data from the database.

Cache.Insert("CachedData", dt, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));

or you can refresh the data on cache every certain number of time. Check Cache Object.

Else, if you need something like cache will refresh it's data from the database only when there's any updates you might want to check SqlCacheDependency Object.


Given a GridView:

 <asp:GridView ID="gv" runat="server">

In the method that calls gv.DataBind(), connect to a dataset that gets populated from the Cache.

System.Web.Caching.Cache cache = HttpContext.Current.Cache;
System.Data.DataSet gvDataSet = cache.Get("gvDataSet") as System.Data.DataSet;
if (gvDataSet == null)
{
        gvDataSet = GetDataSetFromDatabase();
        cache.Insert("gvDataSet",
                      gvDataSet, 
                      null, 
                      System.Web.Caching.Cache.NoAbsoluteExpiration,  
                      TimeSpan.FromMinutes(120), 
                       System.Web.Caching.CacheItemPriority.Default,
                       null);
}
gv.DataSource = gvDataSet;
gv.DataBind();

In the code that updates the DataSet, clear the cache.

 cache.Remove("gvDataSet");

If the code that updates the DataSet is external to the web server, write an HTTP Handler (Generic Handler) that contains the code to clear the cache and call the handler from the external code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜