SqlDependency.OnChange 未在 WinForm 中触发?

SqlDependency.OnChange not firing in WinForm?

我使用 Detecting Changes with SqlDependency 作为我正在编写的代码的示例。我还查看了具有类似代码的其他链接,但其中 none 有效。

本质上,我只是想在对 table [ErrorLog] 进行更改时更改 label1.Text。出于某种原因,OnDependencyChange 没有触发。

我在数据库中启用了 Service Broker

ALTER DATABASE TestDB 
SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE

现在,这是我的完整代码。很短:

public partial class Form1 : Form
{
    private string GetConnectionString()
    {
        return @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=TestDB;Persist Security Info=True;User ID=TestUser;Password=12345;";
    }

    SqlConnection connection;

    public Form1()
    {
        InitializeComponent();

        connection = new SqlConnection(GetConnectionString());
        connection.Open();

        SqlDependency.Start(GetConnectionString());
        i = 0;
    }

    int i;

    void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        i++;
        label1.Text = "Changed: " + i.ToString();
        // Handle the event (for example, invalidate this cache entry).
    }

    void SomeMethod()
    {
        // Assume connection is an open SqlConnection.
        // Create a new SqlCommand object.
        using (SqlCommand command = 
            new SqlCommand("SELECT [ErrorLog].[ID],[ErrorLog].[Project],[ErrorLog].[Form],[ErrorLog].[Message],[ErrorLog].[Exception],[ErrorLog].[InsertDate] " + 
            "FROM [dbo].[ErrorLog]", connection))
        {
            // Create a dependency and associate it with the SqlCommand.
            SqlDependency dependency = new SqlDependency(command);

            // Maintain the reference 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.
            }
        }
    }
}

我检查了 Service Broker 是否已启用并且已启用;以下 returns 1:

SELECT is_broker_enabled 
FROM sys.databases 
WHERE name = 'TestDB';

感谢任何帮助。

谢谢。

除了一件事你做对了所有事情。在 Form1 构造函数中调用方法 SomeMethod() 一次。

对您的 table 数据的所有 后续 更改将触发依赖项更改。