2011-07-05 42 views
1
SqlConnection sqlConn = new SqlConnection(m_connectionString); 
m_cmd = sqlConn.CreateCommand(); 
m_cmd.CommandText = "Select id,name from dbo.instances"; 
m_cmd.Notification = null; 
SqlCacheDependency cacheDepen = new SqlCacheDependency(m_cmd); 

using (SqlDataAdapter sda = new SqlDataAdapter(m_cmd)) 
{ 
    DataSet ds = new DataSet(); 
    sda.Fill(ds, "instance"); 
    Cache.Insert("instance", ds.Tables["instance"],cacheDepen); 
    Cache.Insert("timeNow", DateTime.Now.ToLongTimeString(), cacheDepen); 
} 

我通过SqlCacheDependency创建了一个Web应用程序,Sql Server利用Service Broker在数据更新时通知我。 它在最后两行中引发异常“试图从多个Cache条目引用CacheDependency对象”。 我应该为异常做什么?如何将一个SqlCacheDependency附加到多个Cache项目?

回答

0

我只是放在一起快速控制台应用程序测试重用SqlCacheDependency对象,它工作正常如果你离开了m_cmd.Notification = null;

namespace CacheDependencyReuse 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     SqlCommand cmd = new SqlCommand("SELECT * FROM Products"); 
     SqlCacheDependency dep = new SqlCacheDependency(cmd); 

     // Uncomment this line to get the Exception 
     //cmd.Notification = null; 

     using (SqlConnection conn = new SqlConnection("Data Source=xxx; Initial Catalog=Northwind;User ID=xxx; Password=xxx;")) 
     { 
      SqlDependency.Start(conn.ConnectionString); 
      cmd.Connection = conn; 
      SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
      DataSet productDataSet = new DataSet(); 
      conn.Open(); 
      adapter.Fill(productDataSet); 


      HttpRuntime.Cache.Insert("Products",productDataSet,dep); 
      HttpRuntime.Cache.Insert("Now",DateTime.Now,dep); 

     } 

     Console.ReadLine(); 
    } 
} 

}

我认为,如果你离开Notification操作使用默认值,则运行时将整理你。

+0

对不起,它会在您的建议中再次引发我的代码中的异常。我使用了需要Service Broker支持的SqlDependency,它与控制台应用程序有一些不同。 –

相关问题