日期:2014-05-20  浏览次数:20377 次

SqlDependency缓存依赖问题……
我想用GridView显示一个表中的数据,并缓存,当这个表中数据发生变化时,缓存能自动检测并更新GridView中的显示,数据库使用Sql   Server   2005,利用asp.net   2.0中的SqlDependency应该是可以实现的,但我试了好久都不能成功,代码如下:
protected   void   Page_Load(object   sender,   EventArgs   e)
        {                                
                InitDependency();
                this.Label1.Text   =   DateTime.Now.ToString();              
        }
        public   static   readonly   string   connectionstring   =   @ "Data   Source=(local);Initial   Catalog=db1;Integrated   Security=sspi ";
        public   static   readonly   string   sql   =   "select   id,title,adduser   from   dbo.article ";
        private   static   SqlDependency   dep;
        private   static   SqlCommand   cmd;
        public   void   InitDependency()
        {
                using   (SqlConnection   conn   =   new   SqlConnection(connectionstring))
                {
                        conn.Open();
                        cmd   =   new   SqlCommand(sql,   conn);
                        dep   =   new   SqlDependency(cmd);
                        dep.OnChange   +=   new   OnChangeEventHandler(DependencyChanged);                      
                        this.GridView1.DataSource   =   cmd.ExecuteReader();;
                        this.GridView1.DataBind();
                }
        }
        public   void   DependencyChanged(object   caller,   SqlNotificationEventArgs   e)
        {
                this.Title   =   e.Type.ToString();
                InitDependency();
        }

------解决方案--------------------
步骤一:在SQL Server 2005上执行ALTER DATABASE <DatabaseName> SET ENABLE_BROKER;语句让相应的数据库启用监听服务,以便支持SqlDependency特性。

  这条语句最好在数据库未执行任何事务的情况下执行。

  步骤二:调用SqlDependency.Start(String strConnectionString)方法,在应用程序端启用依赖监听器。

  该方法的参数为一个数据库的连接字符串,该数据库必须已经执行过步骤一的操作。

  对于同一连接字符串,若已经执行过该语句,再次执行不会发生任何异常,但返回值会为False.

  如果是在Web程序中使用,建议可以将该语句放在Application_Start事件中执行。

  监听是基于数据库的,而依赖才可以基于表或者查询。

  步骤三:该步骤分别有两种不同的做法。该阶段必须注意步骤。

  方法A:建立连接对象,再创建一个SqlCommand实例,创建SqlCacheDependency实例,在这步之后再调用Command对象来获取数据(这个顺序很重要)。之后调用Cache的Insert语句建立一个依赖于一个具体查询数据集的Cache项。

SqlConnection conn = new SqlConnection(strConnection);