如何使用SqlDependency读取服务代理队列?

时间:2016-02-15 13:50:03

标签: c# sql-server service-broker sqldependency

public void StartDependency(){    
 _connectionString = ConfigurationManager.ConnectionStrings["GSMIntegrationDatabase"].ConnectionString;

queueName = "RequestQueue";

SqlDependency.Start(_connectionString, queueName);    
}     



  public void RegisterDependency()
    {             
        try
        {
            SqlConnection connection = new SqlConnection(_connectionString);
            string queries = "Select SourceFieldName, DestFieldName from Integration.tblMap;" +
                            "Select ShortName, LongName, ObjName from Integration.tblSystem";
            SqlCommand command = new SqlCommand(queries, connection);

            //Monitor the Service Broker, and get notified if there is change in the query result
            SqlDependency dependency = new SqlDependency(command, "Service=ReceiveNotificationService;local database=GSMRevamp", Int32.MaxValue);

            //Fire event when message is arrived
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            connection.Close();
        }
        catch (Exception ex)
        {
             throw ex;
        }            
    }

此方法方法使用Onchange方法

注册数据
    void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        try
        {
            var info = e.Info;
            var source = e.Source;
            var type = e.Type;

            Console.WriteLine("Onchange executed");

            SqlDependency dependency = sender as SqlDependency;

            dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
            RegisterDependency(); //Re-register dependency is required after a notification is received everytime


        }
        catch(Exception ex)
        {

            throw ex;
        }                           
    }

通过使用此代码,我可以监控队列 我想使用SqlDependency从服务代理队列中获取数据。 每当数据库中的任何数据立即进入队列时,应立即触发SqlDependency OnChange 但我没有得到任何解决方案。

0 个答案:

没有答案