You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用SqlDependency.Start时抛出NullReferenceException的问题求助

调用SqlDependency.Start时抛出NullReferenceException的问题求助

我的代码如下:

using System;
using System.Data.SqlClient;

namespace asldf
{
    class Program
    {
        private static string connectionString = "Server=.\\SQLEXPRESS;Database=Sample;User id=ad;Password=Pass1234;";
        private static SqlDependency sqlDependency;

        static void Main()
        {
            try
            {
                Console.WriteLine("Starting SqlDependency...");
                SqlDependency.Start(connectionString, "SQLDependencyQueue"); // Start dependency first

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new ArgumentNullException("Connection string cannot be null or empty.");
                }
               
                Console.WriteLine("SqlDependency started.");

                MonitorVolumeStore();

                Console.WriteLine("Monitoring changes. Press Enter to quit.");
                Console.ReadLine();

                Console.WriteLine("Stopping SqlDependency...");
                SqlDependency.Stop(connectionString);
                Console.WriteLine("SqlDependency stopped.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred in Main: {ex.Message}");
            }
        }

        private static void MonitorVolumeStore()
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    string query = "SELECT Date, InstrumentTocken, Volume, FullVolume, LTP, TotalBuyers, TotalSellers FROM VolumeStore WHERE InstrumentTocken = 11087106";

                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        Console.WriteLine("Creating SqlDependency...");
                      
                        Console.WriteLine("SqlDependency started.");

                        sqlDependency = new SqlDependency(command); // Initialize here
                        sqlDependency.OnChange += OnVolumeStoreChange;
                        Console.WriteLine("SqlDependency created.");

                        connection.Open();
                        Console.WriteLine("Connection opened.");
                        command.ExecuteReader();
                        Console.WriteLine("Query executed.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred in MonitorVolumeStore: {ex.Message}");
            }
        }

        private static void OnVolumeStoreChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine("New row added to VolumeStore with InstrumentTocken = 11087106");

            sqlDependency.OnChange -= OnVolumeStoreChange;
            MonitorVolumeStore();

            FetchLatestVolumeStoreRow();
        }

        private static void FetchLatestVolumeStoreRow()
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    string query = @"
                    SELECT TOP 1 Date, InstrumentTocken, Volume, FullVolume, LTP, TotalBuyers, TotalSellers
                    FROM VolumeStore
                    WHERE InstrumentTocken = 11087106
                    ORDER BY Date DESC";

                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        connection.Open();
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                DateTime date = reader.GetDateTime(0);
                                int instrumentTocken = reader.GetInt32(1);
                                int volume = reader.GetInt32(2);
                                int fullVolume = reader.GetInt32(3);
                                decimal ltp = reader.GetDecimal(4);
                                int totalBuyers = reader.GetInt32(5);
                                int totalSellers = reader.GetInt32(6);

                                Console.WriteLine($"Date: {date}, InstrumentTocken: {instrumentTocken}, Volume: {volume}, FullVolume: {fullVolume}, LTP: {ltp}, TotalBuyers: {totalBuyers}, TotalSellers: {totalSellers}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred in FetchLatestVolumeStoreRow: {ex.Message}");
            }
        }
    }
}

不过现在我遇到了一个问题:调用SqlDependency.Start(connectionString, "SQLDependencyQueue");的时候抛出了NullReferenceException。

我已经执行了以下SQL操作来配置权限和服务:

ALTER SERVER ROLE sysadmin ADD MEMBER ad;
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO ad;
ALTER DATABASE Sample SET ENABLE_BROKER;

希望大家能帮忙分析一下问题出在哪里,谢谢!

备注:内容来源于stack exchange,提问作者Aditya Bokade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:43:02