brady gaster

yadnb

Automatically Reloading DataSet using Cache (Problem, need help!)

So i've done this before, but for the life of me can't figure out why i can't do it again. When you place a DataSet into the web server's cache, it stands to reason that at some point, you'll want to once again reload the same cache item with the DataSet, once again from the database itself. Solution? Use the CacheItemRemovedCallback delegate to basically call the same routine that queries the data, builds a new DataSet, and places it back into the cache automatically, say every 10 minutes or so.

Thing is, if i use the code below, the CacheItemRemovedCallback delegate i specify gets called right away, and then never again. Anyone seen this before? Solutions?

Here's the code:

public class CachedAuthors : System.Web.UI.Page

{

protected System.Web.UI.WebControls.DataGrid dg;

DataSet dsPubs;

CacheItemRemovedCallback cb = null;

private void Page_Load(object sender, System.EventArgs e)

{

LoadData();

}

 

public void ReCache(string name, object o, CacheItemRemovedReason reason)

{

CacheData();

StreamWriter writer = new StreamWriter(@"C:\CacheLog.txt",true);

writer.WriteLine(DateTime.Now.ToString());

writer.Close();

}

 

void LoadData()

{

dsPubs = new DataSet();

CacheData();

dsPubs = (DataSet)Cache["dsPubs"];

dg.DataSource = dsPubs.Tables[0];

dg.DataBind();

}

 

void CacheData()

{

if(Cache["dsPubs"] == null)

{

cb =

new CacheItemRemovedCallback(this.ReCache);

 

SqlDataAdapter da = new SqlDataAdapter("select * from authors",

"Data Source=(local); User ID=sa; Password=pass4Sql; initial catalog=pubs");

da.Fill(dsPubs);

Cache.Insert("dsPubs",

dsPubs,

null,

DateTime.Now.AddSeconds(10),

TimeSpan.Zero,

CacheItemPriority.High,

cb);

 

Cache["dsPubs"] = dsPubs;

}

}

 

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler(this.Page_Load);

 

}

#endregion

}

Comments

royo@iserializable.com (Roy Osherove) said:

Well, I'm not sure why It's being called right away but I might have a clue as to why it's not called after 10 seconds.
The callback isn't called until you access the cache item. So, if you access the cache item after 30 seconds, only then will the callback be called first.
# February 9, 2004 6:37 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)