[英]Why SqlDependency.OnChange is not being fired?
在过去 3 天努力解决这个问题之后,最后我把我的问题放在这里。
我正在尝试使用 SignalR 和 SqlDependency 构建实时应用程序。 显然,SQLDependency 不起作用。 但是,我的 SignalR 工作正常,因为我尝试了许多不需要数据库交互的功能。
下面是我的代码。 这是我参考的。
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");
}
我的 SqlDependency.OnChange 事件,即 dependency_OnChange 不会在数据库更新时触发。
我已经尝试了所有方法,例如授予权限
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();
}
确保您了解这些依赖项的工作原理(例如 - 在您收到一条通知后 - 您需要重新注册才能获得后续通知)。 或者更好的是,使用一些包装库,比如这个。
你可以用这个简单的例子来测试它:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.