我已经使用Microsofts指南使用sqldependency创建测试Web应用程序。 对于我的数据库,我使用的是Northwind数据库。似乎,依赖关系不起作用,因为我期待对表和标签进行imidiate更新。 此外,代理已启用。
这里是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Caching;
namespace WebDependency
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString();
SqlDependency.Start(GetConnectionString());
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command = new SqlCommand(GetSQL(), connection))
{
SqlCacheDependency dependency = new SqlCacheDependency(command);
int numberOfSeconds = 3;
DateTime expires = DateTime.Now.AddSeconds(numberOfSeconds);
Response.Cache.SetExpires(expires);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Response.AddCacheDependency(dependency);
connection.Open();
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}
}
}
private string GetConnectionString()
{
return "Data Source=(LocalDB)\\MSSqlLocalDB;Initial Catalog=Northwind;Integrated Security=True";
}
private string GetSQL()
{
return "Select CategoryName, Description from dbo.Categories";
}
}
}
答案 0 :(得分:1)
这是我认为您正在寻找的完整示例。
Polling for database changes: SqlDependency, SignalR is Good