SQLDependency不会更新

时间:2016-10-20 08:18:14

标签: asp.net sqldependency

我已经使用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";
    }
}
}

1 个答案:

答案 0 :(得分:1)

  1. 您需要在global.asa
  2. 的Application_Start中启动sqlDependency
  3. 触发器实际触发时没有事件处理程序。
  4. 这是我认为您正在寻找的完整示例。

    Polling for database changes: SqlDependency, SignalR is Good