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. USB2.0协议笔记

    1.概述     USB(Universal Serial Bus)具有传输速率快,可热插拔等显著特点,应用已经十分广泛,目前的相当多的设备已经支持最新的USB3.0协议.理论上USB1.1的传输速度 ...

  2. php判断爬虫

    function checkrobot($useragent = ''){ static $kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos ...

  3. 自己写的一个DirectUI库,基础控件基本都已实现

    http://download.csdn.net/detail/pcradio/9254881 http://blog.csdn.net/pcradio

  4. js合计

    Js合计行: 可以先循环行,然后按行获取这行带有你定义的class的td,取得这些td的 text后相加,最终赋值到这行的“合计”单元格就行了 var trslength = $("#dat ...

  5. HTML5音频,视频播放

    1.此方法可支持多种浏览器 <audio controls="controls"> <source src="1.mp3" ></ ...

  6. [LeetCode]题解(python):081 - Search in Rotated Sorted Array II

    题目来源 https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ Follow up for "Search in ...

  7. (转帖)C++中自己实现的split函数

    由于太久远了,已经忘记作者是谁了,如果看到了,真的对不起,希望能给我留个言(我的QQ:543451622) void split(const string& src, const string ...

  8. ECSHOP不同商品分类调用不同模板

    1.在ecs_category 表 添加 template 字段 可以在后台运行sql语句:alter table `ecs_category` Add column template text NO ...

  9. Estimating Project Costs

    The Wideman Comparative Glossary of Common Project Management Terms describes estimating cost as, &q ...

  10. c#中DropDownList控件绑定枚举数据

    c# asp.net 中DropDownList控件绑定枚举数据 1.枚举(enum)代码: private enum heros { 德玛 = , 皇子 = , 大头 = , 剑圣 = , } 如果 ...