繁体   English   中英

SqlDependency.OnChange无法在WinForm中触发?

[英]SqlDependency.OnChange not firing in WinForm?

我使用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';

任何帮助表示赞赏。

谢谢。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM