当数据库更新时如何通知我的程序?

时间:2022-10-28
本文介绍了当数据库更新时如何通知我的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 C# 程序可以查询 SQL Server 数据库的某些值.

I have a C# program that queries the SQL Server database for some values.

目前,应用程序每分钟查询一次数据库,以确保表是最新的.

Currently the application queries the database every minutes to make sure that the table is up to date.

我希望能够做的是查询仅在数据库已更改/更新时完成.当数据库中的某些内容更新时,我如何通知我的程序?

What I would like to be able to do is that the query is only done when the database has been changed / updated. How do I notify my program when something has been updated in the database?

谢谢

推荐答案

轮询数据库不是很优雅的解决方案.

Polling database is not very elegant solution.

SqlDependency 对您的情况很有用.它不使用轮询而是使用通知机制.通知由 Service Broker 在您的数据库中提供,因此需要在您的数据库中启用此服务.OnChange 事件将在指定的表更改(更新、删除、插入...)时引发

SqlDependency from ADO.NET will be useful in your case. It does not use polling but notification mechanism. The notifications are provided by Service Broker in your database, so will need to enable this service in your databse. The OnChange event will raise when specified table changes(update, delete, insert..)

这是一个如何使用SqlDependency的例子:

Here is an example how to use SqlDependency:

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
        connection))
    {

        // Create a dependency and associate it with the SqlCommand.
        SqlDependency dependency=new SqlDependency(command);
        // Maintain the refence in a class member.

        // Subscribe to the SqlDependency event.
        dependency.OnChange+=new
           OnChangeEventHandler(OnDependencyChange);

        // Execute the command.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

来自 http://msdn.microsoft.com/en-us/图书馆/62xk7953.aspx

以下是如何启用 Service Broker(请注意,您将拥有数据库的独占性来执行此操作 - 最好在重新启动 sql server 后执行此操作):http://blogs.sftsrc.com/stuart/archive/2007/06/13/42.aspx(链接失效)

Here is how to enable Service Broker(note that you will have exclusiveness on the database to do that - best do it after restart of the sql server): http://blogs.sftsrc.com/stuart/archive/2007/06/13/42.aspx(Broken link)

可能的替代链接:http://technet.microsoft.com/en-us/library/ms166086(v=sql.105).aspx

这篇关于当数据库更新时如何通知我的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:C# 在你的 winforms 中嵌入 youtube/videos 下一条:当我发出“SaveChanges()"时,Entity Framework 中的默认事务隔离级别是什么?

相关文章

最新文章