C# 使用SqlDependency通知用户

C# 使用SqlDependency通知用户,c#,winforms,sqldependency,C#,Winforms,Sqldependency,我试图通知连接到同一SQLServer的多个应用程序用户某些数据库表上发生的更改。我决定使用SQLDependency类,因为这似乎是最好的方法,但我无法让它工作。非常感谢你的帮助 首先,我创建了SqlWatcher类,以简化使用情况: 从主窗体,用户可以向目标SqlDependency命令表添加一个项,当这种情况发生时,我希望新窗体弹出新闻。这是我的主要表单的外观: public partial class MainForm: Form { private string connect

我试图通知连接到同一SQLServer的多个应用程序用户某些数据库表上发生的更改。我决定使用SQLDependency类,因为这似乎是最好的方法,但我无法让它工作。非常感谢你的帮助

首先,我创建了SqlWatcher类,以简化使用情况:

从主窗体,用户可以向目标SqlDependency命令表添加一个项,当这种情况发生时,我希望新窗体弹出新闻。这是我的主要表单的外观:

public partial class MainForm: Form
{
    private string connectionString = @"data source = .\sqlexpress; initial catalog = Sample1; integrated security = true";
    private static SqlWatcher SqlQueueWatcher;

    public MainForm()
    {
        InitializeComponent();
        InitializeSqlDependency();
    }

    private void InitializeSqlDependency()
    {
        SqlCommand cmd = new SqlCommand();
        cmd = new SqlCommand("SELECT ID, Text FROM dbo.Notifications");
        cmd.CommandType = CommandType.Text;

        //Setup the SQLWatcher
        SqlQueueWatcher = new SqlWatcher(connectionString, cmd);
        SqlQueueWatcher.OnChange += new SqlWatcher.SqlWatcherEventHandler(QueueSQLWatcher_OnChange);
        SqlQueueWatcher.Start();
    }

    private static void QueueSQLWatcher_OnChange(DataSet Result)
    {
        NotificationForm notificationForm = new NotificationForm(Result);
        notificationForm.Show();
    }
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        SqlQueueWatcher.Dispose();
    }
我希望这样,当任何用户向Notifications数据库添加数据时,其他用户都会通过NotificationForm得到通知。谁能告诉我我做错了什么?这两天来我一直在想办法

提前谢谢


另外,如果您对执行相同的通知概念有更好的想法,请随意表达。

如果您告诉我们调试向您显示了什么,以及在哪里可以查看,则可以深入了解以帮助您。有任何事件发生吗?或者这些事件只是没有在hanlders中被看到?@user1522548 QueueSQLWatcher_OnChange事件从未被触发,这就是困扰我的地方。这就好像SqlDependency甚至没有在命令select语句下监视更改一样。您在MSFT中看到了吗?
public partial class MainForm: Form
{
    private string connectionString = @"data source = .\sqlexpress; initial catalog = Sample1; integrated security = true";
    private static SqlWatcher SqlQueueWatcher;

    public MainForm()
    {
        InitializeComponent();
        InitializeSqlDependency();
    }

    private void InitializeSqlDependency()
    {
        SqlCommand cmd = new SqlCommand();
        cmd = new SqlCommand("SELECT ID, Text FROM dbo.Notifications");
        cmd.CommandType = CommandType.Text;

        //Setup the SQLWatcher
        SqlQueueWatcher = new SqlWatcher(connectionString, cmd);
        SqlQueueWatcher.OnChange += new SqlWatcher.SqlWatcherEventHandler(QueueSQLWatcher_OnChange);
        SqlQueueWatcher.Start();
    }

    private static void QueueSQLWatcher_OnChange(DataSet Result)
    {
        NotificationForm notificationForm = new NotificationForm(Result);
        notificationForm.Show();
    }
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        SqlQueueWatcher.Dispose();
    }