Benvenuti da Idea R | Vicenza - Romano di Lombardia (Bergamo)

Blog

Prendere uno smanettone del software degli anni 80, aggiungere un graphic designer di nuova generazione e allungare il tutto con uno studioso di strategie di marketing. Agitare energicamente e si ottiene il blog Idea R.

Come cancellare la cache degli oggetti SqlDataSource

Pubblicato il 12/24/2011
Categorie: Applicazioni Web

La proprietà SqlDataSource.EnableCaching permette di salvare i risultati di una particolare interrogazione al database.
Una volta attivato il caching, se si reimposta EnableCaching a false, il risultato dell'interrogazione non viene più prelevato dalla cache ma viene rieseguito ogni volta.
La cosa che però può sorprendere è che se a questo punto si reimposta EnableCaching a true, vengono riprelevati i dati dalla vecchia cache.

// The Customers table contains PIPPO as the name of the customer 1
SqlDataSource dataSource = new SqlDataSource(myConnectionString, "SELECT Name FROM Customers WHERE CustomerID = 1");
dataSource.EnableCaching = true;
// The query returns PIPPO
 
...
 
// Update the database changing the name of the customer 1 to MINNY
 
...
 
dataSource.EnableCaching = false;
// This time the cache is disabled, so the query returns MINNY
 
...
 
dataSource.EnableCaching = true;
// WARNING! The query returns the old and expired value PIPPO again

Per cancellare la cache dunque non serve a niente impostare EnableCaching a false, ma bisogna procedere utilizzando la proprietà SqlDataSource.CacheKeyDependency.

// The Customers table contains PIPPO as the name of the customer 1
SqlDataSource dataSource = new SqlDataSource(myConnectionString, "SELECT Name FROM Customers WHERE CustomerID = 1");
dataSource.EnableCaching = true;
dataSource.CacheKeyDependency = "MyCacheKey";
if (Cache["MyCacheKey"] == null] Cache["MyCacheKey"] = DateTime.Now;
// The query returns PIPPO
 
...
 
// Update the database changing the name of the customer 1 to MINNY
 
...
 
Cache["MyCacheKey"] = DateTime.Now; // Clear the cache
// Now the query correctly returns MINNY

 

Ti è stato utile l'articolo?

Condividilo allora con i tuoi amici su Facebook!
A te basta solamente cliccare il pulsante qui sotto, ma a noi farai un enorme favore.

 

Sei il lettore numero 17,726.

Commenti

Articolo precedente

Articolo precedente

Menu dropdown con CSS

Articolo successivo

Riflessi sull'acqua con Photoshop

Articolo successivo