Is there something like the FileSystemWatcher for Sql Server Tables?

前端 未结 5 505
广开言路
广开言路 2021-01-13 13:36

i would like my windows service (to be written in .NET) to recognize when new rows are added to a specific table, but instead of pulling the data from the sql-server i would

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 14:42

    Be careful using SqlDependency class to monitor changes in database tables - it has problems with memory leaks. However, you can use your own realization with DDL triggers and SQL Service Broker API or use one of open source projects, e.g. SqlDependencyEx:

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

    Hope this helps.

提交回复
热议问题