使用 sqlNotificationRequest 时的 SQL 客户端异常



我正在按照教程 https://code.msdn.microsoft.com/windowsdesktop/How-to-Execute-the-1e7c35d5 制作一个 c# 应用程序

我与服务器建立了连接,在数据库中创建了所有必要的过程和队列。

public class SqlNotificationRequestRegister
{
private readonly String serviceName;
private readonly Int32 notificationTimeout;
private readonly String connectionString;
private readonly String listenSql;

private SqlNotificationRequest request;
private Task listenTask;
private SqlCommand cmd = null;
// This event will be invoked after the data is changed.
public event EventHandler OnChanged;
public SqlNotificationRequestRegister(String listenSqlStrig, String service, Int32 timeout,
String connString)
{
listenSql = listenSqlStrig;
serviceName = service;
notificationTimeout = timeout;
connectionString = connString;
RegisterSqlNotificationRequest();
}
/// <summary>
/// Begin to monitor the Service Broker queue
/// </summary>
public void StartSqlNotification()
{
listenTask = new Task(Listen);
listenTask.Start();
}
/// <summary>
/// Create a SqlNotificationRequest and invoke the event.
/// </summary>
private void RegisterSqlNotificationRequest()
{
request = new SqlNotificationRequest();
request.UserData = new Guid().ToString();
request.Options = String.Format("Service={0};", serviceName);
request.Timeout = notificationTimeout;
if (OnChanged != null)
{
OnChanged(this, null);
}
}
/// <summary>
/// Monitoring the Service Broker queue.
/// </summary>
private void Listen()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (cmd = new SqlCommand(listenSql, conn))
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cmd.CommandTimeout = notificationTimeout + 120;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i <= reader.FieldCount - 1; i++)
Debug.WriteLine(reader[i].ToString());
}
}
}
}
RegisterSqlNotificationRequest();
}
public void StopSqlNotification()
{
if (cmd != null)
{
cmd.Dispose();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(Boolean disposed)
{
if (disposed)
{
StopSqlNotification();
}
}
public SqlNotificationRequest NotificationRequest
{ get { return request; } }
}

当我运行上面的代码时,我得到一个 sqlexception

类型为"System.Data.SqlClient.SqlException"的异常发生在 系统数据.dll但未在用户代码中处理 对象名称无效 "学生成绩更改消息"。

但我可以在 ServiceBroker 队列中的 ServerExplorer 中看到 StudentGradeChangeMessages。 代码有什么问题?

这可以是服务代理名称,我认为它应该包含在您的项目中。

它已经提到了提供的链接,如下所示

// StudentGradeChangeMessages is the name of the Service Broker service that has 
// been defined. 
private const String serviceName = "StudentGradeChangeNotifications"; 

最新更新