让 SqlChangeMonitor 工作

发布于 2024-12-11 15:21:22 字数 1850 浏览 0 评论 0原文

我试图让 System.Runtime.Caching 命名空间中包含的新 SqlChangeMonitor 功能正常工作,但得到了一些意外的结果。

我有一个简单的控制台应用程序设置为:

static void Main(string[] args)
{
    var cacher = new Cacher();

    cacher.Start();

    Console.WriteLine("Watching for changes...");

    while (true)
    {
        if (cacher.HasData)
        {
            Console.Write(".");
            Thread.Sleep(1000);
        }
        else
        {
            Console.WriteLine();
            Console.WriteLine("Cache EMPTY!");
            Console.ReadLine();
            cacher.Start();
        }
    }
}

Cacher 类定义为:

public class Cacher
{
    private MemoryCache cache = new MemoryCache("test");

    public Boolean HasData
    {
        get { return cache.Contains("data"); }
    }

    public void Start()
    {
        var connectionString = "Data Source=.;Initial Catalog=CachingTest;Integrated Security=True";
        var list = new NameValueCollection();
        var policy = new CacheItemPolicy();

        SqlDependency.Start(connectionString);

        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand("SELECT * FROM dbo.Table_1", connection))
            {
                var dependency = new SqlDependency(command);

                connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    list.Add(reader["Name"].ToString(), reader["Value"].ToString());
                }

                var monitor = new SqlChangeMonitor(dependency);

                policy.ChangeMonitors.Add(monitor);
            }

            cache.Add("data", list, policy);
        }
    }
}

当我运行代码时,我收到等待消息和一个点“.”,一秒延迟,然后是“缓存为空”消息。当我按下一个键重新启动循环后,会重复此操作。

我缺少什么?

I am trying to get the new SqlChangeMonitor feature included in the System.Runtime.Caching namespace to work and am getting some unexpected results.

I have a simple console application setup as:

static void Main(string[] args)
{
    var cacher = new Cacher();

    cacher.Start();

    Console.WriteLine("Watching for changes...");

    while (true)
    {
        if (cacher.HasData)
        {
            Console.Write(".");
            Thread.Sleep(1000);
        }
        else
        {
            Console.WriteLine();
            Console.WriteLine("Cache EMPTY!");
            Console.ReadLine();
            cacher.Start();
        }
    }
}

The Cacher class is defined as:

public class Cacher
{
    private MemoryCache cache = new MemoryCache("test");

    public Boolean HasData
    {
        get { return cache.Contains("data"); }
    }

    public void Start()
    {
        var connectionString = "Data Source=.;Initial Catalog=CachingTest;Integrated Security=True";
        var list = new NameValueCollection();
        var policy = new CacheItemPolicy();

        SqlDependency.Start(connectionString);

        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand("SELECT * FROM dbo.Table_1", connection))
            {
                var dependency = new SqlDependency(command);

                connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    list.Add(reader["Name"].ToString(), reader["Value"].ToString());
                }

                var monitor = new SqlChangeMonitor(dependency);

                policy.ChangeMonitors.Add(monitor);
            }

            cache.Add("data", list, policy);
        }
    }
}

When I run the code, I get the Waiting message and a single dot '.', the one second delay, then the "Cache Empty" message. This is repeated after I press a key to restart the loop.

What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪若未夕 2024-12-18 15:21:22

事实证明,我原来的问题是由于在 SELECT 语句中使用星号 (*) 通配符引起的。当我列出列名称时,缓存就开始正常工作。

我还想在缓存更新/清除时收到代码通知。 ChangeMonitor 的 NotifyOnChanged 方法不起作用,因为该方法仅供内部使用。

事实证明,CacheItemPolicy 对象有两个回调:RemovedCallback 和 UpdateCallback,可用于这些目的。只需将这些属性设置为代码中的方法并执行所需的操作即可。

鉴于缺乏 SqlChangeMonitor 上的可用文档,我希望这可以对遇到这些问题的其他人有所帮助。

It turns out that my original problem was caused by using the asterisk (*) wildcard in the SELECT statement. As soon as I listed the column names, the cache started working properly.

I also wanted to receive notifications in code when the cache has been updated/cleared. The NotifyOnChanged method of the ChangeMonitor does not work as this is intended for internal use.

As it turns out, the CacheItemPolicy object has two callbacks: RemovedCallback and UpdateCallback that may be used for these purposes. Simply set these properties to methods in code and take the desired action.

Given the lack of documentation available on the SqlChangeMonitor, I hope this may be of assistance to anyone else running into these issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文