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. Qt Model/View(官方翻译,图文并茂)

    http://doc.trolltech.com/main-snapshot/model-view-programming.html 介绍 Qt 4推出了一组新的item view类,它们使用mode ...

  2. 20145211 《Java程序设计》第4周学习总结——园日涉以成趣

    编程思想DRY和Once and Only Once DRY DRY原则的为"每一个知识都必须在系统内必须是单一的,明确的,权威的,具有代表性.当DRY的原则成功应用,在系统中,任何单一元素 ...

  3. 9Types of Leader

    Using the Enneagram Personality Types: The Perfectionist. The People Pleaser. The Achiever. The Indi ...

  4. JS之tagNaem和nodeName

    nodeName是节点的属性,tagName是元素的属性.元素是节点的子集.不是任何节点都有tagName的,比如文本节点,仅有nodeName属性. 这个和css中的倾斜和斜体的关系是一样的.不是所 ...

  5. Selenium2学习-035-WebUI自动化实战实例-033-页面快照截图应用之三 -- 区域截图(专业版)

    之前有写过两篇博文讲述了 WebUI 自动化测试脚本中常用的截图方法,敬请参阅如下所示链接: 浏览器显示区域截图 浏览器指定区域截图 那么当需要截取的区域不在浏览器显示窗口范围之内时,之前的方法显然无 ...

  6. asp.net中控件的Attributes用法

    在点击保存时通常会验证输入框是否为空,一般我们会在按钮控件中添加OnClientClick=“return Check();”事件,并通过javascript来处理. 下面是另一种方法,在后台.cs代 ...

  7. 转帖:解决jquery.js在myeclipse中报错的问题

    转载地址:http://tieba.baidu.com/p/1993753087 从官方下载的jquery.js在myeclipse始终用个大大的红叉,看着很不爽,如何解决呢:jquery.js在my ...

  8. 我的工具箱之MySql Front 5.3

    下载地址:http://pan.baidu.com/s/1i4sJpNB 这款软件用来连接MySql,作为前端使用. 它功能全面,方便快捷,如果说有缺点的话,sql窗口中不能执行选择的部分有遗憾. 2 ...

  9. windows server 2008服务器IIS绑定阿里云域名

    一.打开Internet 信息服务(IIS)管理器   二.将你的网站放到服务器目录下,比如D盘下的WWW文件夹.   三.在IIS中,添加网站,网站的物理路径指向第二部中创建的网站.   五.在绑定 ...

  10. python中几个常用的算术函数

    1.lambda函数(匿名函数) lambda函数使用方式:lambda[参数1,参数2....]:表达式,列表 实例如下: lambda x : x * 2,[1,2,3,4] lambda 2.r ...