本節的範例示範如何利用 ASP.NET SqlCacheDependency 物件,間接使用 SqlDependency。 SqlCacheDependency 物件會使用 SqlDependency 來接聽通知,並正確更新快取。
注意
此範例程式碼假設您已藉由執行啟用查詢通知中的指令碼來啟用查詢通知。
關於範例應用程式
此範例應用程式會使用單一 ASP.NET 網頁,在 GridView 控制項中顯示 AdventureWorks SQL Server 資料庫的產品資訊。 當頁面載入時,程式碼會將目前的時間寫入至 Label 控制項。 然後會定義 SqlCacheDependency 物件,並在 Cache 物件上設定屬性,以儲存快取資料長達三分鐘。 然後,程式碼會連線到資料庫並擷取資料。 當頁面載入且應用程式正在執行時,ASP.NET 將從快取中擷取資料,您可以透過注意頁面上的時間不會變更來驗證這一點。 如果監視的資料變更,ASP.NET 就會讓快取失效,並以全新的資料重新填入 GridView 控制項,進而更新 Label 控制項中顯示的時間。
建立範例應用程式
遵循下列步驟,以建立並執行範例應用程式:
建立新的 ASP.NET 網站。
開啟頁面的類別模組並新增下列指示詞:
using Microsoft.Data.SqlClient; using System.Web.Caching;在頁面的
Page_Load事件中新增下列程式碼:// using Microsoft.Data.SqlClient; protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString(); // Create a dependency connection to the database. SqlDependency.Start(GetConnectionString()); using (SqlConnection connection = new SqlConnection(GetConnectionString())) { using (SqlCommand command = new SqlCommand(GetSQL(), connection)) { SqlCacheDependency dependency = new SqlCacheDependency(command); // Refresh the cache after the number of minutes // listed below if a change does not occur. // This value could be stored in a configuration file. int numberOfMinutes = 3; DateTime expires = DateTime.Now.AddMinutes(numberOfMinutes); Response.Cache.SetExpires(expires); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true); Response.AddCacheDependency(dependency); connection.Open(); GridView1.DataSource = command.ExecuteReader(); GridView1.DataBind(); } } }新增兩個協助程式方法:
GetConnectionString和GetSQL。 定義的連接字串會使用整合式安全性。 驗證所使用的帳戶具有必要的資料庫使用權限,且範例資料庫AdventureWorks已啟用通知。// using Microsoft.Data.SqlClient; private string GetConnectionString() { // To avoid storing the connection string in your code, // you can retrieve it from a configuration file. return "Data Source=(local);Integrated Security=true;" + "Initial Catalog=AdventureWorks;"; } private string GetSQL() { return "SELECT Production.Product.ProductID, " + "Production.Product.Name, " + "Production.Location.Name AS Location, " + "Production.ProductInventory.Quantity " + "FROM Production.Product INNER JOIN " + "Production.ProductInventory " + "ON Production.Product.ProductID = " + "Production.ProductInventory.ProductID " + "INNER JOIN Production.Location " + "ON Production.ProductInventory.LocationID = " + "Production.Location.LocationID " + "WHERE ( Production.ProductInventory.Quantity <= 100 ) " + "ORDER BY Production.ProductInventory.Quantity, " + "Production.Product.Name;"; }
測試應用程式
應用程式會快取 Web 表單上顯示的資料,如果沒有任何活動,則每隔三分鐘就會重新整理一次。 如果資料庫發生變更,就會立即重新整理快取。 從 Visual Studio 執行應用程式,以將頁面載入瀏覽器。 顯示的快取重新整理時間表示上次重新整理快取的時間。 等候三分鐘,然後重新整理頁面,即會導致回傳事件發生。 頁面上顯示的時間已經變更。 如果您在三分鐘內重新整理頁面,則頁面上顯示的時間將維持不變。
現在,使用 Transact-SQL UPDATE 命令來更新資料庫中的資料,並重新整理頁面。 顯示的時間現在表示已使用資料庫的新資料來重新整理快取。 雖然快取已更新,但在發生回傳事件之前,頁面上顯示的時間不會變更。