Summary

There isn't a lot of documentation on the internet about how to use the SqlChangeMonitor with the new MemoryCache class in .NET 4.0, so I thought I would add my example:

Database Preparation

The first step is to prepare your database for SqlChangeMonitor. This feature uses the SQL Server Service Broker to setup a notification event that fires to notify when data changes that would change the returned recordset of a query, so we have to enable the service broker on our database:

Hide   Copy Code
ALTER DATABASE database_name SET TRUSTWORTHY ON WITH ROLLBACK IMMEDIATE
ALTER DATABASE database_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
ALTER AUTHORIZATION ON DATABASE::database_name TO sa

With that out of the way, we can continue on to setting up the cache in code…

Code

Hide   Shrink   Copy Code
public bool IsInMaintenanceMode()
{
bool inMaintenanceMode; if (MemoryCache.Default["MaintenanceMode"] == null)
{
CacheItemPolicy policy = new CacheItemPolicy(); string connStr = "MY CONNECTION STRING"; SqlDependency.Start(connStr); using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand command = new SqlCommand(
"Select MaintenanceMode From dbo.MaintenanceMode", conn))
{
command.Notification = null; SqlDependency dep = new SqlDependency(); dep.AddCommandDependency(command); conn.Open(); inMaintenanceMode = (bool)command.ExecuteScalar(); SqlChangeMonitor monitor = new SqlChangeMonitor(dep); policy.ChangeMonitors.Add(monitor);
}
} MemoryCache.Default.Add("MaintenanceMode", inMaintenanceMode, policy);
}
else
{
inMaintenanceMode = (bool)MemoryCache.Default.Get("MaintenanceMode");
} return inMaintenanceMode;
}

This code is a simple way to cache a value that specifies whether the application is currently in maintenance mode. The dbo.Maintenance table contains a single row with a single bit column. This code will allow your application to continuously check to see if it should go into maintenance mode, without hammering your database.

When the value changes in the database, the application receives a notification that it should invalidate the cache. Then, in the next call to IsInMaintenanceMode, MemoryCache.Default["MaintenanceMode"] returns null, causing it to re-register the notification. Just what we want.

Notes

  • You must call SqlDependency.Start first, otherwise it just doesn't work.
  • Your SQL Command must follow the guidelines located at http://msdn.microsoft.com/en-us/library/ms181122(SQL.100).aspx. There are lots of things to consider about how you build your query, so pay close attention to this document.
  • After adding your command object to the SqlDependency object, you must execute the command at least once, otherwise it will not register the notification.
  • After executing the command once, you can dispose of your connection. Behind the scenes, .NET will keep a connection open to your SQL Server to listen for the notification.

I hope this helps some people out. I know I spent way too much time looking for documentation that just didn't exist.

Edits

  • I have attached a sample project illustrating the use of the code above. It is a simple Console application that just shows how you might use this. Run the SQL script in the attached code to create a database, then run the application. Once it is running, change the value of "MaintenanceMode" in the table. You will see when it is hitting the database, and when it is using the cache. I hope this provides a better example of usage.

翻译:  需要先对数据库执行 命令

ALTER DATABASE database_name SET TRUSTWORTHY ON WITH ROLLBACK IMMEDIATE
ALTER DATABASE database_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
ALTER AUTHORIZATION ON DATABASE::database_name TO sa 再就是sql语句的要求
"列名必须写出来(不能用*),不能用top,不能用函数,包括聚合函数,不能用子查询,包括where后的子查询,不能用外连接,自连接,不能用临时表,不能用变量,不能用视图,不能垮库,而且表名之前必须加类似dbo这样的前缀"
很多限制

.NET 4.0 MemoryCache with SqlChangeMonitor的更多相关文章

  1. ZAM 3D 制作简单的3D字幕 流程(二)

    原地址:http://www.cnblogs.com/yk250/p/5663907.html 文中表述仅为本人理解,若有偏差和错误请指正! 接着 ZAM 3D 制作简单的3D字幕 流程(一) .本篇 ...

  2. ZAM 3D 制作3D动画字幕 用于Xaml导出

    原地址-> http://www.cnblogs.com/yk250/p/5662788.html 介绍:对经常使用Blend做动画的人来说,ZAM 3D 也很好上手,专业制作3D素材的XAML ...

  3. 微信小程序省市区选择器对接数据库

    前言,小程序本身是带有地区选着器的(网站:https://mp.weixin.qq.com/debug/wxadoc/dev/component/picker.html),由于自己开发的程序的数据是很 ...

  4. osg编译日志

    1>------ 已启动全部重新生成: 项目: ZERO_CHECK, 配置: Debug x64 ------1> Checking Build System1> CMake do ...

  5. .NET Core 2.0迁移技巧之MemoryCache问题修复

    对于传统的.NET Framework项目而言,System.Runtime.Caching命名空间是常用的工具了,其中MemoryCache类则常被用于实现内存缓存. .NET Core 2.0暂时 ...

  6. Asp.net Core2.0 缓存 MemoryCache 和 Redis

    自从使用Asp.net Core2.0 以来,不停摸索,查阅资料,这方面的资料是真的少,因此,在前人的基础上,摸索出了Asp.net Core2.0 缓存 MemoryCache 和 Redis的用法 ...

  7. 在ASP.NET Core 2.0中使用MemoryCache

    说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...

  8. 【Core内存】.NET Core 2.0中使用MemoryCache

    说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...

  9. C# MemoryCache 类[转载]

    原网址:http://www.cmono.net/post/read/156 MemoryCache 类是.Net .0推出的类库,主要是为了方便在Winform和Wpf中构建缓存框架的 Object ...

随机推荐

  1. Bulk Insert & BCP执行效率对比(续)

    上回由于磁盘空间(约70G)不足,导致Bulk Insert和BCP导入中途失败:今次统一一些操作,以得到Bulk insert与BCP分别执行效率: 1. 15435390笔数据,21.7G csv ...

  2. 在express中使用Mongoose连接MongoDB

    为何要学Mongoose? Mongoose是MongoDB的一个对象模型工具,封装了MongoDB对文档的的一些增删改查等常用方法,让NodeJS操作Mongodb数据库变得更加灵活简单. 0.安装 ...

  3. Android开发-修改AVD路径

    最近清理系统的时候发现C盘下有个.android文件夹占了大概10G的空间,这可怎么办,后来证实是AVD的缘故,只能修改AVD路径了. 以下是修改AVD路径的方法: 1.创建新的环境变量,ANDROI ...

  4. apache httpclient 4.5 兼容 http https

    String responseContent = ""; try { SSLContextBuilder contextBuilder = new SSLContextBuilde ...

  5. TortoiseGit 的使用

    日常用法 (1) 创建新库 在文件夹中按右键, 选择Git Create repository here 就可以创建库了. 在出现的窗口中, 不勾选选项, 直接按OK 在目录中就会出现一个名为.git ...

  6. Oracle中 根据 file# 和 block# 找到对象

    我们在10046生产的trace 文件里经常看到下面的信息. 表示系统在等待散列读取某个文件号的某个块开始的8个块. WAIT #6: nam='db file scattered read' ela ...

  7. PHP登陆Session验证

    关键字:PHP Session 登陆 验证 本文地址:http://www.cnblogs.com/txw1958/p/php-login-check-session.html 首先,在MySQL数据 ...

  8. 选择时区的命令tzselect

    选择时区的命令tzselect tzselectPlease identify a location so that time zone rules can be set correctly.Plea ...

  9. centos vmware centos6.6 64位 kvm虚拟化安装配置 第四十二节课

    centos vmware centos6.6 64位 kvm虚拟化安装配置     第四十二节课 上半节课 下半节课 f

  10. Android 使用PullToRefreshExpandableListView不能setAdapter的问题

    private PullToRefreshExpandableListView lv; lv = (PullToRefreshExpandableListView) findViewById(R.id ...