SQLDependency Onchange事件始终在没有数据更改的情况下触发

时间:2015-04-19 06:50:54

标签: asp.net sqldependency

我在控制台项目中使用它 .NET Framework:4.5

在我的测试代码中,SQLDependency onChange总是触发,尽管数据库中没有数据更改。

class Program
{
private static string _connStr;

static void Main(string[] args)
{
    _connStr = "data source=xxx.xxx.xx.xx;User Id=xxx;Password=xxx; Initial Catalog=xxx";
    SqlDependency.Start(_connStr);
    UpdateGrid();
    Console.Read();
}


private static void UpdateGrid()
{
    using (SqlConnection connection = new SqlConnection(_connStr))
    {
        using (SqlCommand command = new SqlCommand("select msgdtl,msgid From NotifyMsg", connection))
        {
            command.CommandType = CommandType.Text;
            connection.Open();
            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

            SqlDataReader sdr = command.ExecuteReader();
            Console.WriteLine();
            while (sdr.Read())
            {
                Console.WriteLine("msgdtl:{0}\t (msgid:{1})", sdr["msgdtl"].ToString(), sdr["msgid"].ToString());
            }
            sdr.Close();
        }
    }
}

private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    UpdateGrid();
}

当我开始跑步时,onChange事件触发并且永不停止。但是我的数据库没有变化。

2 个答案:

答案 0 :(得分:2)

尝试检查SqlNotificationEventArgs方法中的dependency_OnChnage对象。看起来你有错误。我有一次相同的SqlDependency行为,并且通过将select msgdtl,msgid From NotifyMsg更改为select msgdtl,msgid From dbo.NotifyMsg(已添加dbo语句)解决了问题。

但是我应该警告你:小心使用SqlDependency类 - 它有problems内存泄漏。 Hovewer,您可以使用SqlDependency类的开源实现 - SqlDependencyEx。它使用数据库触发器和本机Service Broker通知来接收有关表更改的事件。这是一个用法示例:

int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
          TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) 
{
    sqlDependency.TableChanged += (o, e) => changesReceived++;
    sqlDependency.Start();

    // Make table changes.
    MakeTableInsertDeleteChanges(changesCount);

    // Wait a little bit to receive all changes.
    Thread.Sleep(1000);
}

Assert.AreEqual(changesCount, changesReceived);

使用SqlDependecyEx,您可以单独监视INSERT,DELETE,UPDATE并在事件args对象中接收实际更改的数据(xml)。希望这有帮助。

答案 1 :(得分:0)

有一个SqlDependency的自定义实现,它会报告更改的表记录:

   var _con= "data source=.; initial catalog=MyDB; integrated security=True";

   static void Main()
   {
       using (var dep = new SqlTableDependency<Customer>(_con, "Customer"))
       {
           dep.OnChanged += Changed;
           dep.Start();

           Console.WriteLine("Press a key to exit");
           Console.ReadKey();

           dep.Stop();
        }
   }

   static void Changed(object sender, RecordChangedEventArgs<Customer> e)
   {
       if (e.ChangeType != ChangeType.None)
       {
           for (var index = 0; index < e.ChangedEntities.Count; index++)
           {
               var changedEntity = e.ChangedEntities[index];
               Console.WriteLine("DML operation: " + e.ChangeType);
               Console.WriteLine("ID: " + changedEntity.Id);
               Console.WriteLine("Name: " + changedEntity.Name);
               Console.WriteLine("Surame: " + changedEntity.Surname);
           }
       }
   }

以下是链接:[https://tabledependency.codeplex.com]