12
我目前有一个数据库从遗留应用程序获取更新。我想利用SQL Service Broker队列,以便在更新记录时将消息放入队列中(使用触发器或其他)。SQL Service Broker和.NET Windows服务 - 最佳实践?
然后我想要一个长时间运行的应用程序(用.NET编写的Windows服务),它不断“侦听”队列以获取消息并为其他应用程序处理消息。
我在网上找到了一些示例代码,只是想知道代码是否稳定。因此,下面是Windows服务类的缩写版本:
public class MyService
{
public void StartService()
{
Thread listener = new Thread(Listen);
listener.IsBackground = true;
listener.Start();
}
private void Listen()
{
while (true)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
string commandText = "WAITFOR (RECEIVE * FROM MyQueue);";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
command.CommandTimeout = 0;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// Process message
}
}
}
}
}
}
您认为如何?代码完全按照我想要的方式工作。但是关掉一个包含SQL命令的新线程的想法永远不会超时 - 在一个无限循环内 - 让我有点紧张。