目前我正在为 SQL 代理而苦苦挣扎。一切似乎都配置得很好,但是队列停止工作并填满了未发送的消息。代理和队列已启用。如果我删除队列和服务并重新创建它们,它会工作一段时间,但稍后会再次停止。我在 sql server 日志中没有看到任何重要错误。那么可能导致错误的原因是什么?
谢谢
队列
CREATE QUEUE [dbo].[DataChangeQueue] WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = [dbo].[DataChangeQueueProc] , MAX_QUEUE_READERS = 100 , EXECUTE AS N'dbo'), POISON_MESSAGE_HANDLING (STATUS = ON) ON [PRIMARY]
服务
CREATE SERVICE [DataChangeService] AUTHORIZATION [dbo] ON QUEUE [dbo].[DataChangeQueue] ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])
C#
public DatabaseNotificationService()
{
SqlDependency.Start(m_SQLConnectionString, "DataChangeQueue");
if (IsAccessGranted())
{
ConnectToDatabase();
}
}
~DatabaseNotificationService()
{
SqlDependency.Stop(m_SQLConnectionString, "DataChangeQueue");
}
private void ConnectToDatabase()
{
using (SqlConnection sqlConnection = new SqlConnection(m_SQLConnectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = GetSQLCommandText();
sqlCommand.Notification = null;
if (m_SQLDependency != null)
{
m_SQLDependency.OnChange -= DependencyOnChange;
m_SQLDependency = null;
}
m_SQLDependency = new SqlDependency(sqlCommand, "Service=DataChangeService;Local Database=aspnetdb", 1800);
m_SQLDependency.OnChange += DependencyOnChange;
sqlCommand.ExecuteReader();
}
sqlConnection.Close();
}
}
private void DependencyOnChange(object sender, SqlNotificationEventArgs e)
{
using (SqlConnection sqlConnection = new SqlConnection(m_SQLConnectionString))
{
sqlConnection.Open();
using (SqlCommand cmd2 = sqlConnection.CreateCommand())
{
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = GetOnChangeSQLCommandText();
using (SqlDataReader sqlDataReader = cmd2.ExecuteReader())
{
if (sqlDataReader != null)
{
sqlDataReader.Read();
List<String> keys = new List<String>(m_Clients.Keys);
foreach (String key in keys)
{
IDatabaseNotificationCallbackContract client;
if (m_Clients.TryGetValue(key, out client))
{
if (((ICommunicationObject)client).State == CommunicationState.Opened)
{
client.SendNotificationToClients(sqlDataReader.GetValue(0).ToString());
}
else
{
m_Clients.Remove(key);
}
}
}
}
}
}
sqlConnection.Close();
}
if (m_SQLDependency != null)
{
m_SQLDependency.OnChange -= DependencyOnChange;
m_SQLDependency = null;
}
//Reconnect to database for listening to following changes.
ConnectToDatabase();
}