I want my database (SQL) to notify or push updates to client application

半世苍凉 提交于 2019-11-28 20:28:35

Query Notification will push to a Service Broker service, not directly to your application. See The Mysterious Notification to understand how it works. Your application is waiting for notifications by posting a WAITFOR(RECEIVE) statement on the database. Which implies that each of the 100 clients is occupying one SQL Server worker thread (which are limited, see max worker threads option). I've seen this working in production with +1000 clients (after bumping up the max worker threads option) but I would advise against it.

My recommendation would be to have one service monitoring for change, using SqlDependency/QueryNotifications. This service would then push notifications, using WCF for instance, to all your running apps. You would subscribe to generic changes (the table Foo was changed), not to specific ones (the row x in table Foo was inserted).

As a general rule SqlDependency/Query Notifications can only inform you that data has changed, but it won't push the new data. The application must refresh its local datasets by running the queries again, once notified.

dyatchenko

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 just UPDATE, avoiding DELETE and INSERT. Hope this helps.

If you don’t update databse manually and all data manipulation are in your application, you should to detect changes in application service layer or business layer instead of db in case you depend on database technology and going to other databases will be difficult. In other hand if you have manual update on db or dependency to db is not important you can use CDC (chane data capture) and push changes into service broker and your application pop changes from service broker then send them to client by bidirectional http communication technology same as SignalR.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!