【发布时间】:2017-11-16 16:03:54
【问题描述】:
第一次使用 SQL Dependency...但是在浏览了几个示例之后,我觉得我做的一切都是正确的。我检查了代理是否已启用。我进一步检查了我的查询是否正确。我根本没有收到任何异常!所有一切似乎都应该正常工作......但事实并非如此,而且我不知道如何开始对其进行故障排除而不会引发任何异常。
非常感谢任何帮助!
这是我的课:
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();
}
【问题讨论】:
-
我对 sql 依赖项的熟悉程度相当有限,但我想知道您是否连接了 SQL Profiler 以查看您在服务器上实际执行的操作。
-
按照设计,这个初始化应该发生在 Global.asax.Application_Start 或 Startup.cs。
-
@Programmer 你是对的......我实际上只是在几分钟前在另一个问题之后切换了它。但即使在启动级别,它也产生了相同的结果。
-
这是给 signalR 的吗?如果是这样,我已经通过远程连接到他们的机器帮助为几个客户构建了这个。这是一件复杂的事情,但如果我知道它是 signalR,那么我会要求您添加 Hub 代码。
-
@Programmer 不,虽然 SignalR 可能更适合我使用 SQL 依赖项的用途,即我正在模仿消息传递/通知应用程序。它是一个简单的 WinForms Tray(NotifyIcon) 应用程序。
标签: c# .net sql-server sqldependency