SqlDependency不会触发/触发事件

时间:2014-12-23 15:26:01

标签: c# sql-server sql-server-2008 notifications sqldependency

我已经按照一些教程在我的SQL Server数据库中的表中发生更改时向我的应用程序发送通知。这是我的听众课程:

class dbListener
{
    public dbListener() 
    {
        Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");

        SqlDependency.Stop(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        connection.Open();
        SomeMethod();
    }
    SqlConnection connection;
    void SomeMethod()
    {
        // Assume connection is an open SqlConnection.
        // Create a new SqlCommand object.

        SqlCommand command = new SqlCommand("SELECT CODVEI FROM dbo.ArchivioErogazioni", connection);
        // Create a dependency and associate it with the SqlCommand.
        command.Notification = null;  // ---> DO I NEED IT??
        SqlDependency dependency = new SqlDependency(command);
        // Maintain the refence in a class member.
        // Subscribe to the SqlDependency event.
        dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
        // Execute the command.
        command.ExecuteReader();
    }
    // Handler method
    void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        // Handle the event (for example, invalidate this cache entry).
        MessageBox.Show("ikjkjkj");
        Debug.WriteLine("fkldjkfjklgjf");
        SomeMethod();
    }

    void Termination()
    {
        // Release the dependency.
        SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
    }
}

它不会正确触发事件。在应用程序的开头,它向我显示消息框(它在事件管理中进行测试)一次或两次,我不知道为什么。然后,当我从SQL Server Management Studio编辑数据库中的值时,我得到消息框或0或1或2次,然后它再也不会触发。

在我的数据库中,我执行了这个脚本:

USE master ;
GO
ALTER DATABASE IN4MATICSystem_Pie SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
GO
ALTER AUTHORIZATION ON DATABASE::IN4MATICSystem_Pie to sa;

我肯定犯了一个大错误.....哪一个?

更新

在T McKeown的提示之后,这是我的代码(仍然无法正常工作,它在启动时向我显示2或3个消息框,然后没有):

class dbListener
{
    public dbListener() 
    {
        Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");

        SqlDependency.Stop(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
        connection.Open();
        SomeMethod();
    }
    SqlConnection connection;

    SqlCommand command;
    void SomeMethod()
    {
        // Assume connection is an open SqlConnection.
        // Create a new SqlCommand object.

        if (command == null)
        {
            command = new SqlCommand("SELECT * FROM dbo.ArchivioErogazioni", connection);
            // Create a dependency and associate it with the SqlCommand.
        }
        else
        {
            command.Notification = null;  // this cancels any previous notifcation object
        }
        SqlDependency dependency = new SqlDependency(command);
        // Maintain the refence in a class member.
        // Subscribe to the SqlDependency event.
        dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
        // Execute the command.
        command.ExecuteReader();
    }
    // Handler method
    void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change) 
        { 
            // Handle the event (for example, invalidate this cache entry).
            MessageBox.Show("ikjkjkj");
            Debug.WriteLine("fkldjkfjklgjf");
            SqlDependency dependency = (SqlDependency)sender;
            dependency.OnChange -= OnDependencyChange; 
            //dependency.OnChange -= OnDependencyChange;
            SomeMethod();
        }
    }

    void Termination()
    {
        // Release the dependency.
        SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
        connection.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
    // Handle the event (for example, invalidate this cache entry).
    MessageBox.Show("ikjkjkj");
    Debug.WriteLine("fkldjkfjklgjf");

   SqlDependency dependency =
    (SqlDependency)sender;
    dependency.OnChange -= OnDependencyChange;
    SomeMethod(); //re-register
}

修改SomeMethod()

SqlConnection connection;
SqlCommand command;   <-- make command instance var

void SomeMethod()
{
    // Assume connection is an open SqlConnection.
    // Create a new SqlCommand object.

    if ( command == null )
    {
       command = new SqlCommand("SELECT * FROM dbo.ArchivioErogazioni", connection);
      // Create a dependency and associate it with the SqlCommand.
    }
    else{
       command.Notification = null;  // this cancels any previous notifcation object
    }
    SqlDependency dependency = new SqlDependency(command);
    // Maintain the refence in a class member.
    // Subscribe to the SqlDependency event.
    dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
    // Execute the command.
    command.ExecuteReader();
}

调用此函数,它是否返回true?

private bool CanRequestNotifications()
{
// In order to use the callback feature of the
// SqlDependency, the application must have
// the SqlClientPermission permission.
try
{
    SqlClientPermission perm =
        new SqlClientPermission(
        PermissionState.Unrestricted);

    perm.Demand();

    return true;
}
catch
{
    return false;
}
}