SqlDependency 是否锁定 table?

does SqlDependency lock table?

我想在我的项目中使用 SqlDependency,但是我想要的 table 正被多个程序用于非常重要的目的。因此,他们必须能够在 SqlDependency 运行时插入此 table。这可能吗?

我已阅读 this 个问题,但没有找到我的答案。

为了回答您的问题,SqlDependency 不会 'lock' table,但在高写入环境中可能 increase lock contention,因为它使用与索引视图相同的机制来检测对基础数据。

但是,它应该很合适,除非:

  • 更改频率可能很高。要定义 'high',您确实需要测试您的生态系统,但建议的准则是,如果您的数据每秒更改多次,它可能不适合您:不能保证 SqlDependency 的响应时间,并且回调机制并非设计用于可靠地处理许多并发更改,您需要在 every 更改时得到通知。此外,SqlDependency 可以在基础 table 上增加 blocking/contention,因为用于跟踪更改的索引会形成写入频率高的瓶颈。

  • 您打算将 SqlDependency 构建到直接访问数据库的客户端应用程序(例如桌面应用程序)中,并且其中会有很多实例 .在这种情况下,大量的侦听器、队列和消息可能会影响数据库性能并且效率低下。在这种情况下,您需要在考虑 SqlDependency 之前在数据库和应用程序之间放置一些中间件。

  • 您需要可靠地收到每次更改的通知。 SQL Server 中的 SqlDependency 底层机制将为每次更改生成通知,但 .NET 方面的设计并不是以多线程方式处理它们:如果通知到达时 SqlDependency 的工作线程正在运行已经在处理另一个通知,它将被错过。在这种情况下,您可以改用 SqlNotificationRequest

  • 您需要立即收到更改通知(即保证亚秒级)。 SqlDependency 并非设计为低延迟;它专为缓存失效场景而设计。

如果 SqlDependency 不适合,请查看 MSDN 上的 Planning for Notifications and underlying Query Notifications 页面以获得更多指导和替代建议。否则请参阅下文,了解有关如何根据正在使用的基础技术评估性能的更多详细信息。

SqlDependency 在很大程度上依赖于两项关键的 SQL 服务器技术:query notifications (based on indexed views), and service broker. It effectively hooks into the mechanism that updates an indexed view whenever the underlying data changes. It adds a message to a queue for each change, and service broker handles the messaging and notifications. In cases where the write frequency is very high, SQL Server will work hard to handle the writes, keep its 'indexed view' up-to-date, as well as queueing and serving up the many resulting messages. If you need near-instant notification, this may still be the best approach, otherwise have a look at either polling, or using an After Update trigger which perhaps uses Service Broker as suggested on MSDN.