SqlDependency.OnChange not firing in WinForm?

倾然丶 夕夏残阳落幕 提交于 2019-12-20 05:12:21

问题


I used Detecting Changes with SqlDependency as example for the code that I'm writing. I've also looked at other links with similar code, but none of them work.

Essentially, I simply want to change label1.Text when a change has been made to table [ErrorLog]. For some reason, OnDependencyChange is not firing.

I've enabled Service Broker in the database:

ALTER DATABASE TestDB 
SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE

Now, here's my complete code. It's very short:

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.
            }
        }
    }
}

I checked if service broker is enabled and it is; the following returns 1:

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

Any help is appreciated.

Thanks.


回答1:


You are doing everything correctly except one thing. Call the method SomeMethod() once in your Form1 constructor.

All subsequent changes to your table data will trigger the dependency change.



来源:https://stackoverflow.com/questions/38024866/sqldependency-onchange-not-firing-in-winform

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