wtf512
wtf512

Reputation: 4738

SQLDependency Onchange event always firing without data change

I'm using it on a console project.
.NET Framework: 4.5

In my test code, SQLDependency onChange always firing although there is no data changes in Database.

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();
}

when I start running, onChange event fires and never stop. But there is no change in my databse.

Upvotes: 2

Views: 2295

Answers (2)

Christian Del Bianco
Christian Del Bianco

Reputation: 1043

there is a custom implementation of SqlDependency that report you the changed table records:

   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);
           }
       }
   }

Here is the link: [https://tabledependency.codeplex.com]

Upvotes: 0

dyatchenko
dyatchenko

Reputation: 2343

Try to check the SqlNotificationEventArgs object in the dependency_OnChnage method. It looks like you have an error there. I had the same SqlDependency behavior one time and the problem was solved by changing select msgdtl,msgid From NotifyMsg to select msgdtl,msgid From dbo.NotifyMsg (The dbo statement has been added).

But I should warn you: be careful using SqlDependency class - it has the problems with memory leaks. Hovewer, you can use an open source realization of the SqlDependency class - SqlDependencyEx. It uses a database trigger and native Service Broker notification to receive events about the table changes. This is an usage example:

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);

With SqlDependecyEx you are able to monitor INSERT, DELETE, UPDATE separately and receive actual changed data (xml) in the event args object. Hope this help.

Upvotes: 5

Related Questions