gpt4 book ai didi

c# - 为什么没有触发 SqlDependency.OnChange?

转载 作者:行者123 更新时间:2023-11-30 23:14:12 26 4
gpt4 key购买 nike

在过去 3 天为这个问题苦苦挣扎之后,我终于把我的问题放在这里了。

我正在尝试使用 SignalR 和 SqlDependency 构建一个实时应用程序。显然,SQLDependency 不工作。但是,我的 SignalR 工作正常,因为我尝试了许多不需要数据库交互的函数。

下面是我的代码。 Here是我正在引用。

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
NotificationHub objNotificationHub;

protected void Application_Start()
{
string connectionString = WebConfigurationManager.AppSettings["SQL"];
// SQL Command Text
string commandText = "SELECT status From tableTask";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
SqlDependency.Start(connectionString);
command.ExecuteReader().Dispose();
objNotificationHub = new NotificationHub();
}
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
objNotificationHub.SendNotifications();
}
}
}

NotificationHub.cs(SignalR 中心类)

[HubMethodName("sendNotifications")]
public void SendNotifications()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
context.Clients.All.recieveNotification("asbc");
}

My SqlDependency.OnChange event i.e. dependency_OnChange is not firing on database update.

授权等方法我都试过了

ALTER DATABASE MyDB SET ENABLE_BROKER

还有很多这样的。但没有成功。

有没有我遗漏的东西。另外,有什么方法可以检查我的代码是否正在与 SQL Server 通信?

TIA

最佳答案

您没有执行您的命令,这是获取通知所必需的:

SqlDependency.Start(connectionString);
string commandText = "SELECT status From dbo.tableTask"; // don't forget schema here
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
command.ExecuteReader().Dispose();
objNotificationHub = new NotificationHub();
}

确保您了解这些依赖项是如何工作的(例如 - 在您收到一个通知后 - 您需要重新注册才能获得后续通知)。或者更好的是,使用一些包装器库,例如 this一个。

你可以用这个简单的例子来测试它:

static void Main(string[] args) {
var cs = "connection string";
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
SqlCommand command = new SqlCommand("select ErrorCode from dbo.Error", connection);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += OnChange;
SqlDependency.Start(cs);
command.ExecuteReader().Dispose();
}
Console.ReadKey();
}

private static void OnChange(object sender, SqlNotificationEventArgs e) {
Console.WriteLine(e.Info);
}

关于c# - 为什么没有触发 SqlDependency.OnChange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com