SQL依赖事件未被触发

时间:2017-11-16 16:03:55

标签: c# .net sql-server sqldependency

第一次使用SQL Dependency ...但在经过几个例子后,我觉得我正在做的一切都是正确的。我检查过Broker是否已启用。我进一步检查了我的查询是否正确。我没有收到任何例外!所有的一切似乎都应该有效......但事实并非如此,而且我不知道如何开始对其进行故障排除而不会抛出任何异常。

非常感谢任何帮助!

这是我的班级:

public class NotificationEvent
{
    private delegate void RateChangeNotification(DataTable table);
    private SqlDependency dependency;
    string ConnectionString = @"ConnectionString";
    string UserName = Environment.UserName;

    public async void StartNotification()
    {
        SqlDependency.Start(this.ConnectionString, "UserNotificationsQueue");
        SqlConnection connection = new SqlConnection(this.ConnectionString);
        await connection.OpenAsync();

        SqlCommand command = new SqlCommand();           
        command.Connection = connection;
        command.CommandType = CommandType.Text;
        command.CommandText = string.Format("SELECT [NotificationID],[UserFrom],[UserTo],[DateTimeSent],[Notification] FROM [dbo].[PersonnellNotifications]", UserName);
        command.Notification = null;


        this.dependency = new SqlDependency(command, "Service=PostUserNotificationsQueue;", Int32.MaxValue);
        dependency.OnChange += new OnChangeEventHandler(this.SqlDependencyOnChange);
        await command.ExecuteReaderAsync();
    }

    private void SqlDependencyOnChange(object sender, SqlNotificationEventArgs eventArgs)
    {
        if (eventArgs.Info == SqlNotificationInfo.Invalid)
        {
            Console.WriteLine("The above notification query is not valid.");
        }
        else
        {
            Console.WriteLine("Notification Info: " + eventArgs.Info);
            Console.WriteLine("Notification source: " + eventArgs.Source);
            Console.WriteLine("Notification type: " + eventArgs.Type);
        }
    }


    public void StopNotification()
    {
        SqlDependency.Stop(this.ConnectionString, "QueueName");
    }
}

我正在从另一个类IniatializeComponent()中初始化它,如下所示:

private void InitializeComponent()
{
    // Initialize SQL Dependancy        
    ne.StartNotification();
}

2 个答案:

答案 0 :(得分:1)

我刚刚在我的代码及其工作中测试了以下内容。我简化了你的代码。请查看这是否有效,并且您正在使用Db Change更改OnNotificationChange。

public async void RegisterForNotification()
{
     var connectionString = @"ConnectionString";
     using (var connection = new SqlConnection(connectionString))
     {
         await connection.OpenAsync();

          var queryString = "Your Query String";
          using (var oCommand = new SqlCommand(queryString, connection))
          {
              // Starting the listener infrastructure...
              SqlDependency.Start(connectionString);

               var oDependency = new SqlDependency(oCommand);
               oDependency.OnChange += OnNotificationChange;

               // NOTE: You have to execute the command, or the notification will never fire.
                await oCommand.ExecuteReaderAsync();
            }
        }
    }


private void OnNotificationChange(object sender, SqlNotificationEventArgs e)
{
   Console.WriteLine("Notification Info: " + e.Info);
    //Re-register the SqlDependency. 
   RegisterForNotification();
}

答案 1 :(得分:1)

您是否设置了SQLClientPermission?看到: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-query-notifications

// Code requires directives to
// System.Security.Permissions and
// System.Data.SqlClient

private bool CanRequestNotifications()
{
    SqlClientPermission permission =
        new SqlClientPermission(
        PermissionState.Unrestricted);
    try
    {
        permission.Demand();
        return true;
    }
    catch (System.Exception)
    {
        return false;
    }
}