关于c#:SqlCacheDependency删除回调在Cache.Add之后直接触发

SqlCacheDependency remove callback fires directly after Cache.Add

我对sqlcacheDependency有一个问题,我不能完全理解它。当使用通知查询时,当我向缓存添加某些内容时,cacheitemremovedcallback将立即启动(当我使用databaseentryname和tablename时,它起作用,但这对我来说很钝)。我已经检查了大约20次http://msdn.microsoft.com/en-us/library/ms181122.aspx,但仍然找不到我做错了什么。

我使用的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
string connString = MsSqlUtil.GetConnectionString();
System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connString);
System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connString,"Product");
SqlDependency.Start(connString);

Product product = ProductProvider.Get(10);

using (SqlConnection connection = new SqlConnection(connString))
{

  SqlCommand cmdProduct = new SqlCommand(@"
  SET ANSI_NULLS ON
  SET ANSI_PADDING ON
  SET ANSI_WARNINGS ON
  SET CONCAT_NULL_YIELDS_NULL ON
  SET QUOTED_IDENTIFIER ON
  SET NUMERIC_ROUNDABORT OFF
  SET ARITHABORT ON
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED
  SELECT dbo.Product.ProductId, dbo.Product.Name FROM dbo.Product WHERE dbo.Product.ProductId = 10"
, connection);

  SqlCacheDependency myProductDependency = new SqlCacheDependency(cmdProduct);

  if (connection.State == ConnectionState.Closed)
  {
    connection.Open();
  }

  using (SqlDataReader reader = cmdProduct.ExecuteReader())
  {
    while (reader.Read())
    {
    }
  }

  HttpContext.Current.Cache.Add("Product:10", product, myProductDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, OnRemove);

}


//Callback
public static void OnRemove(string key, object cacheItem, System.Web.Caching.CacheItemRemovedReason reason)
{
//this fires directly and the reason is always DependencyChanged however nothing has changed in the database, weird!
}

我知道查询一定有问题,因为http://msdn.microsoft.com/en-us/library/ms181122.aspx告诉我"如果这些选项或隔离级别设置不正确,则在执行select语句后立即触发通知。"但是,我不知道出了什么问题。productID列的类型为int,名称为nvarchar(50)


在SQL事件探查器中观察qn:subscription事件类。运行测试用例。将触发一个事件,同时触发EventSubClass值订阅。TextData将完全包含订阅通知信息、源和类型(我认为它将在EventTextxml元素中)。

通过这个,您将确切地知道您的查询是如何不符合要求的,并且您可以相应地解决这个问题。