.NET 4.0 MemoryCache with SqlChangeMonitor
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:
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
Copy Codepublic 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.Startfirst, 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
SqlDependencyobject, 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的更多相关文章
- ZAM 3D 制作简单的3D字幕 流程(二)
原地址:http://www.cnblogs.com/yk250/p/5663907.html 文中表述仅为本人理解,若有偏差和错误请指正! 接着 ZAM 3D 制作简单的3D字幕 流程(一) .本篇 ...
- ZAM 3D 制作3D动画字幕 用于Xaml导出
原地址-> http://www.cnblogs.com/yk250/p/5662788.html 介绍:对经常使用Blend做动画的人来说,ZAM 3D 也很好上手,专业制作3D素材的XAML ...
- 微信小程序省市区选择器对接数据库
前言,小程序本身是带有地区选着器的(网站:https://mp.weixin.qq.com/debug/wxadoc/dev/component/picker.html),由于自己开发的程序的数据是很 ...
- osg编译日志
1>------ 已启动全部重新生成: 项目: ZERO_CHECK, 配置: Debug x64 ------1> Checking Build System1> CMake do ...
- .NET Core 2.0迁移技巧之MemoryCache问题修复
对于传统的.NET Framework项目而言,System.Runtime.Caching命名空间是常用的工具了,其中MemoryCache类则常被用于实现内存缓存. .NET Core 2.0暂时 ...
- Asp.net Core2.0 缓存 MemoryCache 和 Redis
自从使用Asp.net Core2.0 以来,不停摸索,查阅资料,这方面的资料是真的少,因此,在前人的基础上,摸索出了Asp.net Core2.0 缓存 MemoryCache 和 Redis的用法 ...
- 在ASP.NET Core 2.0中使用MemoryCache
说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...
- 【Core内存】.NET Core 2.0中使用MemoryCache
说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...
- C# MemoryCache 类[转载]
原网址:http://www.cmono.net/post/read/156 MemoryCache 类是.Net .0推出的类库,主要是为了方便在Winform和Wpf中构建缓存框架的 Object ...
随机推荐
- 蓝牙HID协议笔记
1.概述 The Human Interface Device (HID)定义了蓝牙在人机接口设备中的协议.特征和使用规程.典型的应用包括蓝牙鼠标.蓝牙键盘.蓝牙游戏手柄等.该协议改编自USB ...
- nrf51822裸机教程-GPIO
首先看看一下相关的寄存器说明 Out寄存器 输出设置寄存器 每个比特按顺序对应每个引脚,bit0对应的就是 引脚0 该寄存器用来设置 引脚作为输出的时候的 输出电平为高还是低. 与输出设置相关的 还有 ...
- OC接收数据时毫秒转date时间最简略方法
一般项目中接收后台的数据会收到毫秒格式的date,需要换算成正规日期格式,这时候我们的好朋友command + c 和 command + v就得出来帮忙了: 可以复制使用如下方法: + (NSStr ...
- URL编码数据转换为JSON数据
NSString *urlString; urlString=[self URLDecodedString:urlString]; -(NSString *)URLDecodedString:( ...
- php--列表展示(小实训一月考)
效果图:
- RTSP交互命令简介及过程参数描述
目录 [hide] 1 RTSP消息格式 2 简单的rtsp交互过程 3 rtsp中常用方法 3.1 OPTION 3.2 DESCRIBE 3.3 SETUP 3.4 PLAY 3.5 PAUSE ...
- MAGENTO程序结构图
Magento程序结构图(Program Structure Diagram): /app – 程序根目录 /app/etc – 全局配置文件目录 /app/code – 所有模块安装其模型和控制器的 ...
- sublime text2 操作及插件
sublime text2 1. 文件快速导航: 这是sublime上面很好用的功能之一,ctrl+p可以调出窗口,菜单上的解释是gotoanythings ,确实如其所言,调出窗口后,直接输入关键字 ...
- JS-005-常见下拉列表 Select 和 datalist
下拉列表在我们日常的网页浏览的过程中,随处可见,是 web 编程过程中大家非常熟悉的一个页面元素,随着 HTML 语言的日益强大,其在广大攻城狮的手中可谓是千变万化,有了很多不同的实现方式.本文主要以 ...
- 开发报表时将已有User做成下拉列表,第一项为label为ALL,value为null
SELECT 'All' AS LABLE_NAME, NULL AS USER_NAMEUNION ALLSELECT USER_NAME AS LABLE_NAME, USER_NAME from ...