2015-11-04 89 views
0

我的确有一个问题:我正在研究ASP.Net Web窗体和C#应用程序,并且我使用gridView来显示表中的数据,所以我决定缓存。SqlDependency和SqlCacheDependency之间的差异

我做了

aspnet_regsql -ed -E -d Store 
aspnet_regsql -et -E -d Store-t Customers 

,并在web.config修改:

<caching> 
     <sqlCacheDependency pollTime="2000" enabled="true"> 
     <databases> 
      <add name="Store" connectionStringName="StoreConnectionString"/> 
     </databases> 
     </sqlCacheDependency> 
    </caching> 

但现在我必须决定是否使用SqlDependency

<%@ OutputCache Duration=”600″ SqlDependency=”Store:Customers” VaryByParam=”none” %> 

或者使用SqlCacheDependency

private void BindData() { 
    if (Cache["Users"] == null) {    
     SqlCacheDependency dep = new SqlCacheDependency("Store", "Customers"); 
     string connectionString = ConfigurationManager.ConnectionStrings[ 
             "ConnectionString"].ConnectionString; 
     SqlConnection myConnection = new SqlConnection(connectionString); 
     SqlDataAdapter ad = new SqlDataAdapter("SELECT FirstName, LastName " + 
               "FROM Users", myConnection); 
     DataSet ds = new DataSet(); 
     ad.Fill(ds); 
     Cache.Insert("Cust", ds, dep); 
    } 
    gvUsers.DataSource = Cache["Cust"] as DataSet; 
    gvUsers.DataBind(); 
} 

请您告诉我SqlDependencySqlCacheDependency之间有什么区别,哪个更适合我的代码?

回答

0

SqlDependency可能在page指令中用作outputcache的属性,最重要的方面是您必须在Web.config中指定您的connectionstring(因为您可能知道这是安全风险)并且还可以使用poll中的polltime属性。

SqlCacheDependency是一个类,你需要指定想要通过cache.insert或cache.add添加到缓存中的数据,你不需要在Web.config中指定连接字符串,但也许你会可能使用SERVICE_BROKER代替aspnet_regsql和,如果你还决定使用SERVICE_BROKER记得要以指定添加一个Global.asax:

Application_start(){ 
string connectionString = yourdatabaseconnection; 
    System.Data.SqlClient.SqlDependency.Start(connectionString); 
} 

和App_end()

Application_end(){ 
string connectionString = yourdatabaseconnection; 
    System.Data.SqlClient.SqlDependency.Stop(connectionString); 
} 

,因为我”已经使用aspnet_regsql命令我可能会se outputchache指令页面和SqlDependency但具有更大的轮询时间,但我最终的建议是使用SqlCacheDependency并启用SERVICE_BROKER,通过

ALTER DATABASE testdb SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE