Peter Bromberg posted this Rob Howard sample a few days ago :
using System;
using System.Web;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace BlackbeltBLL {
public class BackgroundService : IHttpModule {
static Timer timer;
int interval = 5000;
public String ModuleName {
get { return "BackgroundService"; }
}
public void Init(HttpApplication application) {
// Wire-up application events
if (timer == null)
timer = new Timer(new TimerCallback(ScheduledWorkCallback), application.Context, interval, interval);
}
public void Dispose() {
timer = null;
}
private void ScheduledWorkCallback (object sender) {
HttpContext context = (HttpContext) sender;
Poll(context);
}
void DoSomething (HttpContext context) {
}
#region DB Poll
void Poll (HttpContext context) {
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Northwind"]);
SqlCommand command = new SqlCommand("SELECT * FROM changenotification", connection);
SqlDataReader reader;
string key = ConfigurationSettings.AppSettings["SqlDependency"];
connection.Open();
reader = command.ExecuteReader();
while (reader.Read()) {
string tableKey = String.Format(key, reader["Table"]);
if (context.Cache[tableKey] != null) {
int changeKey = int.Parse( context.Cache[ String.Format(key, reader["Table"])].ToString() );
if (changeKey != int.Parse(reader["ChangeID"].ToString() ))
context.Cache.Remove(tableKey);
}
}
connection.Close();
}
#endregion
}
}
---000---