【问题标题】:SqlDependency.OnChange not firing in WinForm?SqlDependency.OnChange 不在 WinForm 中触发?
【发布时间】:2016-06-25 04:10:41
【问题描述】:

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

本质上,当表[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.
            }
        }
    }
}

我检查了服务代理是否已启用并且已启用;以下返回 1:

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

感谢任何帮助。

谢谢。

【问题讨论】:

    标签: c# winforms visual-studio-2010 sql-server-2008-r2


    【解决方案1】:

    除了一件事,你做的一切都是正确的。在 Form1 构造函数中调用一次方法 SomeMethod()

    对表数据的所有后续更改都会触发依赖项更改。

    【讨论】:

    • 谢谢,效果很好。现在的问题是尝试从这个新线程更新标签:Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2012-10-26
    • 2018-07-16
    • 2011-08-02
    • 2021-10-05
    相关资源
    最近更新 更多