SqlDependency.Start(connectionString) 每次都返回 false

Ale*_*lex 3 c# t-sql asp.net

我设置了可以访问数据库

use DbName
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO dbuser
use DbName
GRANT SELECT ON OBJECT::schema.tableName TO dbuser
Use DbName
GRANT RECEIVE ON QueryNotificationErrorsQueue TO dbuser
ALTER DATABASE DbName SET TRUSTWORTHY ON
use DbName
alter database DbName SET ENABLE_BROKER
Run Code Online (Sandbox Code Playgroud)

但是当我启动SqlDependency时:

bool started = SqlDependency.Start(connectionString);
Run Code Online (Sandbox Code Playgroud)

//started 是 false 然后我得到这个错误

System.Data.dll 中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理其他信息:在不提供选项值的情况下使用 SqlDependency 时,必须在执行添加的命令之前调用 SqlDependency.Start()到 SqlDependency 实例。

C#代码:

private static bool notificationEnabled = false;
private string connString= "Data Source=(local);Initial Catalog=MyDB;UID=dbuser; PWD=pass;";
    public static void EnableNotifications()
    {
        // prevent for calling twice 
        if (notificationEnabled)return; 

        System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connString);
        //startResult is false always
        bool startResult = SqlDependency.Start(connString);
        notificationEnabled = true;
    }
Run Code Online (Sandbox Code Playgroud)

use*_*282 6

尝试将队列名称添加到您的开始:

bool startResult = SqlDependency.Start(connString, queueName)
Run Code Online (Sandbox Code Playgroud)

我还必须将服务名称和超时添加到我的 SqlDependency 构造函数中才能正常工作。(虽然是VB语言,但是你明白了)

dependency = New SqlDependency(command, "Service=" + SERVICE_NAME + ";", Int32.MaxValue)
Run Code Online (Sandbox Code Playgroud)